View Full Version : best way to extend QVariant to support std::string?
TorAn
17th November 2011, 18: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.
Thanks
MarekR22
17th November 2011, 19: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).
ChrisW67
17th November 2011, 22: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>
Q_DECLARE_METATYPE(std::string)
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
qRegisterMetaType<std::string>("std::string");
std::string s("Test");
QVariant v1( QVariant::fromValue<std::string>(s) );
QVariant v2;
v2.setValue(s);
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();
}
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.