What is a role in a QTreeWidgetItem?

11,140

Solution 1

You can use the Qt::UserRole for application specific purposes. Since this data is a QVariant, you can create a QList to set multiple data and after that cast it to QVariant and set the data.

Here is an example:

QTreeWidgetItem* item = new QTreeWidgetItem();
QList<QVariant> dataList;
dataList.append("data 1");
dataList.append("data 2");
QVariant data(dataList);
item->setData(0, Qt::UserRole, data);

Solution 2

The relevant documentation can be found under Qt::ItemDataRole (found through QAbstractItemModel::setData). Roles are used to specify what the data you are passing should be used for. You can use different roles to set the tooltip, font or color of an item, among other things.

Solution 3

Note that item->text() is a convenience equivalent to item->data(Qt::DisplayRole).toString()

Share:
11,140
Nathan
Author by

Nathan

If you can do a half-assed job of anything, you're a one-eyed man in a kingdom of the blind. - Kurt Vonnegut

Updated on June 15, 2022

Comments

  • Nathan
    Nathan about 2 years

    I have a QTreeWidget with several Columns, I add QTreeWidgetItems to it. I try to make the second column contain a numerical value for each Item so I can sort the items by this value

    QTreeWidgetItem has a method called setData(int column, int role, QVariant(data))
    

    I cannot find any documentation on what this role argument is. All I know is that if I set it to 1 or 2, something shows up in the column, if I set it to 0 or >=3, nothing shows up in the column, regardless, the numbers always end up being sorted alphabetically, which is wrong.

  • pi3
    pi3 over 9 years
    You're not limited to Qt:UserRole - it's just the first one you can use for your purposes. You can easily store multiple values without the need to invent a new data type.