c++ - Creating QList of multiple object types -
i need make multiple instances of various class types (classa, classb, classc), , store in single list. is possible create these objects dynamically , add them single qlist? like:
qlist<qobject> mylist; mylist.append(classa()); mylist.append(classb()); mylist.append(classc());
this won't compile because objects not of type qobject. static_cast them qobject, able typeid.name() determine origical types? (to cast them later)?
i found example here of using qlist< qvariant >, compiler complains that:
error: no matching function call 'qvariant::qvariant(classa&)'
for code:
qlist<qvariant> mylist; mylist.append(qvariant(tempobj));
update:
i got compiling creating object during append operation, , using ::fromvalue.
mylist.append(qvariant::fromvalue(classa(1,2,3)));
not sure right. 1 - cause memory leak/problem creating object in append statement? 2 - why need ::fromvalue make work? (does make second copy of object?)
i put qdebug in constructors, , see constructor parameters called twice, copy constructor called once, , default (no parameters) constructor never called. don't understand that...
you can use qvariant
can hold number of different types: qvariant api
to use qvariant
custom type need register metatype system: qmetatype means using q_declare_metatype(myclass)
q_declare_metatype()
qvariant designed holding objects of different types, , used in sorts of qt conventions when programmer wants pass around user-defined types through qt's interfaces when qt has no way of knowing type programmer wants use.
to convert original type use combination of qvariant::canconvert()
, qvariant::value()
:
qvariant v; mycustomstruct c; if (v.canconvert<mycustomstruct>()) c = v.value<mycustomstruct>(); v = 7; int = v.value<int>(); // same v.toint() qstring s = v.value<qstring>(); // same v.tostring(), s "7" mycustomstruct c2 = v.value<mycustomstruct>(); // conversion failed, c2 empty
your custom type must provide:
- a public default constructor,
- a public copy constructor, and
- a public destructor.
the following message
class example of acceptable custom type use in qvariant
class message { public: message(); message(const message &other); ~message(); message(const qstring &body, const qstringlist &headers); qstring body() const; qstringlist headers() const; private: qstring m_body; qstringlist m_headers; };
you declare own "meta-type wrapper" holds type , description of type. simplest example:
template <typename t> class anytype { public: enum the_type { mt_int, mt_string }; anytype(t value, the_type type) : value(value), type(type) { } the_type gettype() { return type; } t getvalue() { return value; } private: t value; the_type type; }
Comments
Post a Comment