Solved QMetaType::registerConverter for a user-defined structure to QString.
-
Hi everyone,
I'm currently working on a project and I need to develop my own conversion from a User-defined structure (let's call it "MyStructure"), which has already been defined as a Q_META_TYPE, to a QString.
Both functions "toQStringFromMyStructure" and "toMyStructureFromQString" are already written.
This is the time where I want to use the QMetaType::registerConverter(MemberFunction function).My pseudo code would be like:
######################HEADER FILE#######################
struct MyStructure { ... }
class MyClass
{
public:
static QString toQStringFromMyStructure(MyStructure myStructure);
static MyStructure toMyStructureFromQString (QString qString);
}######################CPPFILE##########################
// The constructor.
MyClass::MyClass() : m_value(value)
{
QMetaType::registerConverter<MyStructure, QString>(toQStringFromMyStructure);
}######################################################
As you can image, the italic code line doesn't compile and is subject to all kind of errors.
I tried to adapt the given argument, such as "&toQStringFromMyStructure" or "*toQStringFromMyStructure" etc. but neither of them did work actually. Moreover, the Qt Documentation couldn't help me found my issue.Please, do you have any idea ?
Could it be related to the fact that my converter functions are "static" ?
Could it be related to the fact that the registration is done in a class MyClass which is neither the original type nor the targeted type ?Honestly I am totally lost with this - I have no doubt about that - powerful method.
Thank you in advance.
-
Hi
The docs says
bool QMetaType::registerConverter(MemberFunction function)
so if it really means a member function, i doubt a static can be used as
its not a real member function since there is no "this" pointer involved.
So i would 100% try to have them as non static.
Also i wonder if MyClass should be QObject based and have Q_OBJECT macro. -
Hi and welcome to devnet,
Here is a small example:
#include <QCoreApplication> #include <QMetaType> #include <QTextStream> #include <QtDebug> class TestMe { public: TestMe(int value=12): value(value) {} QString toString() const { return QString::number(value); } private: int value; }; Q_DECLARE_METATYPE(TestMe) int main(int argc, char **argv) { QCoreApplication app(argc, argv); QMetaType::registerConverter(&TestMe::toString); TestMe test; QVariant variant; variant.setValue(test); qDebug() << variant.toString(); return 0; }
-
Thank you, both of you.
Since I couldn't solve the problem, I decided to adapt my code according to your example (in particular, I did create a new class which attributes are of type "MyStructure", etc.)
Anyways, it finally worked !
Thanks again,
See you soon !