Search code examples
c++qtqtcoreqvariantqtdbus

Qt DBus property convert to map


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?


Solution

  • 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);