Qt and setData()

Started by
2 comments, last by jnmacd 11 years, 1 month ago

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!

Code makes the man
Advertisement

Its hard to read your code since its not formatted...

but it looks like you are creating sceneItem as a local variable on the stack, then saving the memory address and trying to access it when sceneItem goes out of scope.

You can't do this.

thanks jnmacd, that fixed it. I was using a few examples i found online. oh well. you can't always trust everything on the internet!

are you familiar with Qt?

Code makes the man

thanks jnmacd, that fixed it. I was using a few examples i found online. oh well. you can't always trust everything on the internet!

are you familiar with Qt?

Yes, my main development environment.

This topic is closed to new replies.

Advertisement