How to set a string property to QTreeWidgetItem?

Viewed 1099

I have a list of application specific items uniquely identified by an id. Their names are displayed in a QTreeWidget (one item corresponds to a single QTreeWidgetItem). I would like to somehow attach the corresponding ids to these QTreeWidgetItems so that upon selection changed I can access the id of the corresponding item and do some processing.

QTreeWidgetItem does not inherit from QObject so I cannot use its setProperty function. How could I do this?

2 Answers

Just create some user defined roles for the properties...

typedef enum {
  id_1_role = Qt::UserRole,
  id_2_role,

  id_N_role,
} property_id_role;

Then you can use the normal means of getting/setting the data associated with a QTreeWidgetItem.

QTreeWidgetItem *item = ...

/*
 * Set the property value.
 */
item->setData(column, property_id_role::id_2_role, id_2_value);

/*
 * Get the property value.
 */
auto id_2_value = item->data(column, property_id_role::id_2_role).value<id_2_type>();

Do you know that QTreeWidgetItem has a setData method?

setData(int column, int role, const QVariant &value)

You can use it with your roles. For example:

int your_id = 123;
ui->treeWidget->currentItem()->setData(0,Qt::UserRole,your_id);
qDebug() << ui->treeWidget->currentItem()->data(0,Qt::UserRole);
Related