QT 5 QTreeWidgetItem setData()



  • Currently, i am have a QTreeWidget setup, and it is displaying information properly. Now i am trying to interact with it. When a user clicks on a node of the treeWidget, i need to pass a custom data object thru so i can act accordingly.

    in Editor.h i have the following

    #include <QtWidgets/QMainWindow>
    #include <QtCore/QVariant>
    #include <QMetaType>
    ...
    const int ITEM_NONE = 0;
    const int ITEM_NODE = 1;
    const int ITEM_COMPONENT = 2;
    const int NO_ITEM = 0xFFFFFFFF;

    class SceneItem {
    public:
    SceneItem() { type_ = 0; id_ = 0; }
    SceneItem(unsigned type, unsigned id) { type_ = type; id_ = id; }
    SceneItem(SceneItem* sceneItem) { type_ = sceneItem->type_; id_ = sceneItem->id_; }
    ~SceneItem() { }

    public:
    unsigned int type_;
    unsigned int id_;
    };

    Q_DECLARE_METATYPE(SceneItem*);
    ...
    };

    then inside of Editor.cpp i have the following

    void OnLoad() {
    ...
    SceneItem sceneItem;
    sceneItem.id_ = 1;// scene_->GetID();
    sceneItem.type_ = 1;// ITEM_NODE;

    QVariant sceneItemVariant = qVariantFromValue(&sceneItem);

    item->setData(0, Qt::UserRole, sceneItemVariant);

    ui.sceneTreeWidget->addTopLevelItem(item);
    ...
    }

    i then have a signal setup for itemClicked to pass thru the QTreeWidgetItem, and this works.

    then i try and extract the data as follows

    void Editor::OnSceneTreeItemSelected(QTreeWidgetItem* item, int i) {

    QVariant sceneItemVariant = item->data(0, Qt::UserRole);

    SceneItem* sceneItem = sceneItemVariant.value<SceneItem*>();

    UpdateSceneAttributes(sceneItem);
    }

    when i extract the data, sceneItem has the values of
    id_ = 75661952
    type_ = 0

    Any suggestions of help would be much appreciated!



  • i have solved the issue. SceneItem needs to be created dynamically, and can not be a local static variable


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.