[SOLVED] Custom QVariant crash on drag in QTreeView
-
Hi
I use QStandardItemModel in a QTreeView. On QStandardItem(s) I set QVariant as a pointer to a custom class.
These are the alternatives I tried:
#1 Using void *
@ptrQStandardItem->setData( QVariant::fromValue(static_cast<void*>(ptrMyClass)) , Qt::UserRole+MyRole);@#2 Using custom type registration
@
Q_DECLARE_METATYPE(MyClass*) //right below the class declaration
qRegisterMetaType<MyClass*>("MyClass*"); //in mainpxQStandardItem->setData( QVariant::fromValue(ptrMyClass) , Qt::UserRole+MyRole);
@In both cases, when I just start to drag one item I get crash with debug assert message: "Invalid type to save". When I take out the ->setData line it works without problem. I don't even get the value from that QVariant anywhere in the code, and still have the crash.
I looked the forum but the solutions are mainly related to defining stream operators, but that is the case when object is used as custom QVariant type, not pointer. I don't need to use qRegisterMetaTypeStreamOperators() for a pointer either. Why do I get this error?
Thanks!
-
Draging an item causes the QStandardItem object to be serialized into the QByteArray data member of a QMimeData, which means you need to define and register the stream operators for MyClass*.
-
[quote author="alexisdm" date="1353957735"]Draging an item causes the QStandardItem object to be serialized into the QByteArray data member of a QMimeData, which means you need to define and register the stream operators for MyClass*.[/quote]
Can you please show me an example? Thanks a lot.
-
If the item is only moved within the application, you could write its address in the QDataStream:
@QDataStream &operator<<(QDataStream &out, MyClass * const &rhs) {
out.writeRawData(reinterpret_cast<const char*>(&rhs), sizeof(rhs));
return out;
}QDataStream & operator >> (QDataStream &in, MyClass &rhs) {
in.readRawData(reinterpret_cast<char>(&rhs), sizeof(rhs));
return in;
}// With that line in main
qRegisterMetaTypeStreamOperators<MyClass*>("MyClass*");@ -
Perfect, thanks!!!