问题描述:

I receive data in JSON using a QJsonObject. I also have a QObject-based object holding properties, using Q_PROPERTY(...), for the keys in the JSON. Since Qt now has some more datatypes than JSON how can one check if they are convertible.

The datatypes used in the object typically are one of the following but not limited to

uint

double

QString

QDateTime

bool

The idea is to automatically call setProperty(...) on the QOject derived object for every key/value in the QJsonObject. Since this could fail due to malformed input in the JSON I have to check validity based on the QMetaProperty and QJsonObject/QVariantMap data.

Since this should run generic as a base class implementing manual checks for every datatype fails. I know there is QVariant::isConvertible<T>().

#include <QJsonObject>

#include <QVariant>

#include <QMetaObject>

#include <QMetaProperty>

class Test {

Q_GADGET

Q_PROPERTY(QString test)

QString m_test;

QJsonObject jo;

void call();

}

void Test::call()

{

jo.insert("test",QJsonValue(5));

// This will fail, since int is not convertible to QString implicitly

staticMetaObject->property(staticMetaObject->propertyOffset()).writeOnGadget(this,jo["test"].toVariant());

}

Since I am parsing the JSON before to check if every property would have a corresponding key in the JSON-Object I really like to catch these there already without changing my original object. Something like:

jo["test"].toVariant().canConvert<staticMetaObject->property(staticMetaObject->propertyOffset()).type()>()

网友答案:

Instead of using templated bool QVariant::canConvert<T>() one can use bool QVariant::canConvert(int targetTypeId).

QMetaProperty po = staticMetaObject->property(staticMetaObject->propertyOffset());
jo["test"].toVariant().canConvert(po.type());
相关阅读:
Top