Congratulations to our 2022 Qt Champions!

How to enter and read an Icon image into/from a ListWidget data model with a Delegate

  • Hi,
    I am using a Delegate to retrieve data from a ListWidget data model to be able to control how I display the data in the ListWidgetItem items. My code compiles fine but when I debug the Delegate I can see that the retrieved Icon points to "null". So it seems that the Icon is not being found in the model. I wonder if someone can tell what the problem is. Here are the snippets of the code that are revelant. Thank you!

    In MainWindow construtor: I enter the Icon into the data model of ListWidget

    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
    QVBoxLayout *hlayout = new QVBoxLayout();
    QListWidget *myListWidget = new QListWidget();
    // Setting Delegate
    myListWidget->setItemDelegate(new ListDelegate(myListWidget));

    QListWidgetItem *item = new QListWidgetItem();
    QPixmap pixmap(":/images/arrow.png");
    QIcon ic(pixmap);
    QVariant v(QMetaType::QIcon, &ic);

    //Add Icon to model with custom role
    item->setData(Qt::UserRole + 3, v);

    // Add strings
    item->setData(Qt::DisplayRole, "Wine");
    //item->setData(Qt::UserRole + 1, "Description");

    // BEER
    QListWidgetItem *item2 = new QListWidgetItem();
    item2->setData(Qt::DisplayRole, "Beer");


    In the Delegate: Read Icon and display in ListWidget--

    void ListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    QRect r = option.rect; //rectangle of listitem

    QIcon ic = QIcon(qvariant_cast<QPixmap>( + 3)));
    r = option.rect.adjusted(5, 10, -10, -10);
    ic.paint(painter, r, Qt::AlignVCenter|Qt::AlignRight);


  • you are casting the cariant to a p9xmap, but it contains an icon.
    so add a pixmap in the c'tor or get a qicon out of the variant.

  • That is so funny, how just telling others about your bug, helps you find the solution. I fiddled some more and realized what you just said so I fixed it. Thanks Gerolf for confirming.

    So I replaced this line in the Delegate:
    QIcon ic = QIcon(qvariant_cast<QPixmap>( + 3)));


    QVariant v = + 3);
    QIcon ic = v.value<QIcon>();@

  • And instead of

    QVariant v(QMetaType::QIcon, &ic);

    it is ok to write (and you actually should do this):

    QVariant v(ic);

Log in to reply