Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QStyledItemDelegate: getting QModelIndex::data value by Qt::UserRole in paint() method [Invalid]



  • Hi all,

    I have a subclassed QStyledItemDelegate class where I do some extra painting jobs. I'm setting the delegate on a QTreeWidget, to which I am of course adding QTreeWidgetItems to. I had no problems getting the text of the item by index.data(Qt::DisplayRole). However, wanting to be a bit more fancy, I'm adding more data to each QTreeWidgetItem with QTreeWidgetItem::setData(column, Qt::UserRole, someValue).

    How do I get those values in my QStyledItemDelegate:: paint method? I tried with QModelIndex(Qt::UserRole).toInt() (after checking if I'm at the right rolumn), but I'm not getting the values I'm expecting. I am probably doing something wrong here, but what?



  • What getting a handle to the item itself, something like this:

    MyItem::paint(QPainter *painter,
    const QStyleOptionViewItem &option,
    const QModelIndex &index) const
    {
    QStandardItemModel *model = (QStandardItemModel *) index.model();
    QStandardItem *item = model->itemFromIndex(index);
    QVariant v = item->data( Qt::DecorationRole ); // or UserRole in your case
    ..
    }

    Hope this is of some value to you



  • No, just an int value set via QTreeWidgetItem::setData.

    Sorry, seems like it was my own mistake. I was manipulating data other were, and that tricked me into believing my method of fetching data was wrong.

    Ignore me, please.


Log in to reply