QMetaType::convert failed

996 Views Asked by At

I'm trying to use QMetaType::convert to convert a QJsonValue to another dynamic type. At first, I tested the following code with the dynamic type setting to QString, the conversion was failed.

QJsonValue value("test");
QString string;
if (!QMetaType::convert(&value, QMetaType::QJsonValue, &string, QMetaType::QString))
{
    qDebug() << "failed";
}

Then, I found this static method to check whether the meta system has a registered conversion between two meta types.

qDebug() << QMetaType::hasRegisteredConverterFunction(QMetaType::QJsonValue, QMetaType::QString);

unfortunately, the result was false. Maybe QJsonValue is so complex that the conversion from QJsonValue to QString is not supported. Finally, I tried this, and the result was still false:

qDebug() << QMetaType::hasRegisteredConverterFunction(QMetaType::Int, QMetaType::Int);

It's odd, seems to be, Qt dose not implement the converter functions between basic meta types. And, users can't use QMetaType::registerConverter to register converter function between two basic meta types.

I still can't believe that Qt dosen't implement conversions between basic meta types, is there any initializtion or .pro setting I missed?

1

There are 1 best solutions below

1
kaloskagatos On

I guess you have the QMetaType system and the QVariant class to encapsulate Qt data types on the one hand, and QJsonValue to encapsulate a value in JSON on the other hand.

QMetaType::convert can deal with QVariant data only. What you can do is to extract the QVariant from your QJsonValue and then use the QMetaType system to convert your data you know being a QString.

// Your code
QJsonValue value("test");
QString string ;
if (!QMetaType::convert(&value, QMetaType::QJsonValue, &string, QMetaType::QString))
{
    qDebug() << "failed";
}

// Extract the QVariant data
QVariant variant = value.toVariant() ;

// Two way to test conversion between QVariant and a type
qDebug() << "canConvert template:" << variant.canConvert<QString>() << endl
         << "canConvert parameter:" << variant.canConvert( QMetaType::QString ) ;
if( variant.canConvert<QString>() )
{
   // Convert using QVariant methods
   qDebug() << "QVariant toString:" << variant.toString() ;

   // Convert Using QJsonValue methods
   qDebug() << "QJsonValue toString:" << value.toString() ; // It's just a string representation of the data, not the actual data
}

outputs :

 failed
 canConvert template: true 
 canConvert parameter: true
 QVariant toString: "test"
 QJsonValue toString: "test"

PS: the QJsonValue::Type : String is different from the QVariant::Type : String (QMetaType::QString) so there is no relationship between them.