I'm trying to use custom classes in QAbstractListModel, and the Q_DECLARE_METATYPE doesn't work at all!
To test where the problem is, I've simplified the code as the following:
#include <QMetaType>
#include <QVariant>
#include <QDebug>
typedef int x;
Q_DECLARE_METATYPE(x)
void main() {
QVariant v;
qDebug() << v.canConvert<x>();
}
and the output is still false!
btw, the code I want to implement is like:
namespace ns{
class a {
public:
a(); //default constructor
a(const a&); //copy constructor
~a();
}
}
Q_DECALRE_METATYPE(ns::a);
and when I try to reimplement QAbstractListModel::data like this:
QList<ns::s> list; //this is actually a member field of the custom model.
QVariant MyListModel::data(const QModelIndex& index, int role) const {
Q_UNUSED(role)
return list.at(index.row());
}
the compiler will report and error like:
cannot convert const ns::a to QVariant::Type
Your example is overly simplified as the docs quite clearly state that the class/struct being passed to Q_DECLARE_METATYPE must have a default constructor, a copy constructor and a public destructor: http://qt-project.org/doc/qt-5.0/qtcore/qmetatype.html#Q_DECLARE_METATYPE
That being said, here's a pretty simple example that shows Q_DECLARE_METATYPE working:
#include <QMetaType>
#include <QVariant>
#include <QDebug>
namespace MyNS {
class MyClass {
public:
MyClass() : value(0) { }
MyClass(int value) : value(value) { }
MyClass(const MyClass &other) { value = other.value; }
~MyClass() { }
int getValue() const { return value; }
private:
int value;
};
};
Q_DECLARE_METATYPE(MyNS::MyClass);
int main(int argc, char *argv[])
{
MyNS::MyClass m(15);
QVariant v = QVariant::fromValue(m);
qDebug() << v.canConvert<MyNS::MyClass>();
qDebug() << v.value<MyNS::MyClass>().getValue();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With