Qt DBus property convert to map

988 views Asked by At

I need to get a DBus interface's property, so I did interface.property(name). That returns a QVariant, but the map that a QVariant can return is only QMap<QString, QVariant>, whereas I need QMap<QString, QDBusVariant>. What should I do?

2

There are 2 answers

0
László Papp On BEST ANSWER

I think you are looking for this method as there is no QVariant::toQDBusVariant() method, inherently and rightfully:

T QVariant::​value() const

Returns the stored value converted to the template type T. Call canConvert() to find out whether a type can be converted. If the value cannot be converted, a default-constructed value will be returned.

If the type T is supported by QVariant, this function behaves exactly as toString(), toInt() etc.

Depending on your use case, then you either rebuild the map in one go, or you convert it to your preferred type on the go. Either way, you would use this mechanism as shown by the above example:

QVariant myVariant;
...
QDBusVariant dbusVariant;
if (myVariant.canConvert<QDBusVariant>())
    dbusVariant = myVariant.value<QDBusVariant>();

You can also go as the QDBusVariant example shows:

// retrieve the D-Bus variant
QDBusVariant dbusVariant = qvariant_cast<QDBusVariant>(v);
0
Iharob Al Asimi On

If you want to convert the QMap then

QMap<QString,QVariant> variantMap(initializeVariantMapFunction());
QMap<QString,QDBusVariant> dbusVariantMap;
QMap<QString,QVariant>::const_iterator it;

for (it = variantMap.constBegin() ; it != variantMap.constEnd() ; ++it)
    dbusVariantMap.insert(it.key(), qvariant_cast<QDBusVariant>(it.value()));

But you could of course, leave variantMap as is, and when accessing the value do

QDBusVariant someDBusVariant = qvariant_cast<QDBusVariant>(variantMap.value(key));

You can use QVariant::canConvert to check if the conversion if possible.