I have a really simple QListWidget
object and I want to build a folder list.
When I add an item to my list here is what I do :
void LessCC::on_addFolderButton_clicked()
{
QString dirName = QFileDialog::getExistingDirectory(this, tr("Choose Directory"), QDir::homePath(), QFileDialog::ShowDirsOnly);
QListWidgetItem* newItem = new QListWidgetItem(QIcon(":/resources/icons/folder.png"), dirName, 0, 0);
this->ui->folderListWidget->addItem(newItem);
}
This is working but I want my items to have multiple lines or column of informations (with different style).
I heard about the QStyledItemDelegate but I don't really understand how it works because all other solutions I've found seems really complicated for such simple(?) thing.
Is this the only solution or maybe there is something much more simple I did not see ?
Hope someone can help me.
It's a little difficult to suggest the "best" solution without seeing exactly what you want your list item to look like, but we'll give it a try.
There is actually a great post on the Qt thread here that finally at the end gives all the code they use to create a list sort of like the one they show at the top.
Basically, each item has a large icon, and to the right there is a title and description text, each styled differently.
Creating a custom delegate sounds scary, but it is basically just providing a custom widget for the list. It works essentially like a template. You define what you want your list item to look like, and you paint it using data from list. You just can inherit from QAbstractItemDelegate.
The biggest job is to code the paint function. I'll just show the basics here, but you can reference the link above for a longer example.
So you can see in this code we are getting three bits of data from the list. The icon, the title, and the description. Then we are displaying drawing the icon, and drawing the two text strings how we like. But the important part is getting the data itself. We are basically asking the list to give us the data using the "index" that was passed to us.
You'll notice that each bit of information was retrieved using a different "role". Normally a list has only one thing it displays - which is accessed through the DisplayRole. Icons are stored in the DecorationRole. But if you want to store more stuff, then you start using UserRole. You can store a whole slew of things using UserRole, UserRole +1, UserRole +2 etc....
So how you do you store all this information in each item. Easy...
And finally, how do you make the list display the item using your fancy new delegate?
Hopefully that clarified things a little bit.