Search code examples
c++qtqlistviewqstringlistmodel

How add icon in QListView using QStringListModel?


Is somehow possible to add icons to a ListView using a QStringListModel ?

This is what I'm doing.

QStringListModel* model;
QStringList List;
model->setStringList(List);
ui->listView->setModel(model);
...

model->setData(index, "Test");
model->setData(index,QIcon(":/icon.png"),Qt::DecorationRole);

unfortunately the icon does not appears on the list.

How can I add icons to the list?


Solution

  • QStringListModel does not support roles other than DisplayRole and EditRole.

    Use QStandardItemModel instead in order to display icons via DecorationRole:

    auto model = new QStandardItemModel(this);
    ui->listView->setModel(model);
    model->appendRow(new QStandardItem(QIcon(":/icon.png"), "Test"));