View Full Version : best way to extend QVariant to support std::string?

17th November 2011, 19:37
I found out that I need to extend support of std::string in QVariant. Specifically, to allow std::string as an argument in constructor.
Other then deriving from QVariant, (something like myQVariant : public QVariant) and supplying the signatures for all datatypes that are relevant for me, including std::string - may be there is another way? I am not considering the option of chaging Qt sources.


17th November 2011, 20:19
declare meta type in some header file: Q_DECLARE_METATYPE (http://doc.trolltech.com/latest/qmetatype.html#Q_DECLARE_METATYPE)
just after QApplication is created register new type using: qRegisterMetaType
Now you can use QVaiant with almost any type (requirements are listed in Q_DECLARE_METATYPE documentation).

17th November 2011, 23:26
QVariant is designed to be extended using the mechanisms MarekR22 outlines above. You can then use the named constructor (http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.8) QVariant::fromValue() or QVariant::setValue()

#include <QtCore>
#include <iostream>


int main(int argc, char *argv[])
QCoreApplication app(argc, argv);


std::string s("Test");
QVariant v1( QVariant::fromValue<std::string>(s) );
QVariant v2;

std::string t1 = v1.value<std::string>();
std::cout << t1 << std::endl;
std::string t2 = v2.value<std::string>();
std::cout << t2 << std::endl;

return app.exec();