
Originally Posted by
moijhd
What if I have no control over the type ie the type is defined in a library ?
If the type has a default constructor and can be copied then you can store it in a QVariant.
If the class does not meet the requirements then you can store a pointer (const or not) in a QVariant.
You need to arrange somewhere that Q_DECLARE_METATYPE() is invoked before you try to use the 3rd party type in a QVariant.
#include <QtCore>
// From some library header
class AClass {
public:
AClass() { }
~AClass() { }
AClass(const AClass &other) { }
};
class BClass {
public:
BClass() { }
~BClass() { }
private:
BClass(const BClass &other) { } // cannot be copied
};
// end of header
Q_DECLARE_METATYPE(AClass)
Q_DECLARE_METATYPE(const BClass*)
int main(int argc, char **argv) {
AClass aa;
// later
AClass ar = av.value<AClass>();
const BClass bb;
// later
const BClass *br = bv.value<const BClass*>();
return 0;
}
#include <QtCore>
// From some library header
class AClass {
public:
AClass() { }
~AClass() { }
AClass(const AClass &other) { }
};
class BClass {
public:
BClass() { }
~BClass() { }
private:
BClass(const BClass &other) { } // cannot be copied
};
// end of header
Q_DECLARE_METATYPE(AClass)
Q_DECLARE_METATYPE(const BClass*)
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
AClass aa;
QVariant av = QVariant::fromValue(aa);
// later
AClass ar = av.value<AClass>();
const BClass bb;
QVariant bv = QVariant::fromValue(&bb);
// later
const BClass *br = bv.value<const BClass*>();
return 0;
}
To copy to clipboard, switch view to plain text mode
By the way, can we guard Q_DECLARE_METATYPE through Qt ?
I have no idea what this means.
Bookmarks