Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QT: Problem, How do I return my own QObject derived custom class as “QVariant”?

Tags:

qt

Implementing a derived “QAbstractListModel::data” method.

Q_DECLARE_METATYPE(myType); doesn’t even compile…. returning my custom object results in a compilation error.

How can this be done?

like image 235
JasonGenX Avatar asked Jan 29 '26 16:01

JasonGenX


2 Answers

QVariant::fromValue<QObject *>(object);

replace QObject with your own type, but use Q_DECLARE_METATYPE on it. Keep in mind what you are declaring: the MyType or MyType *. Since you are talking about passing an object from QAbstractItemModel::data, then I suppose that you want to provide a pointer to the object, is this correct? If so, then declare it like this:

typedef MyType * MyTypeStar
Q_DECLARE_METATYPE(MyTypeStar);

This will make MyType * known to the meta-type system.

If you want to pass around the object itself, then declare the way you tried, but make sure that you properly define your type:

Q_DECLARE_METATYPE: This macro makes the type Type known to QMetaType as long as it provides a public default constructor, a public copy constructor and a public destructor. It is needed to use the type Type as a custom type in QVariant.

like image 138
ak. Avatar answered Jan 31 '26 09:01

ak.


Why wont put it inside QVariant as QObject ? qVariantFromValue(youObjectPointer)

like image 37
Kamil Klimek Avatar answered Jan 31 '26 08:01

Kamil Klimek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!