简体   繁体   中英

How to set a string property to QTreeWidgetItem?

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM