Search code examples
c++qtqtreewidgetqtreewidgetitem

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?


Solution

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