如何使用QDBus解析{String的Dict,{String,Variant}的Dict

How do I parse Dict of {String, Dict of {String, Variant}} with QDBus?

本文关键字:Dict String Variant 何使用 QDBus 解析      更新时间:2023-10-16

我正在查询NetworkManager的org.freedesktop.NetworkManager.Settings.Connection接口,并在其上调用"GetSettings"。它以Dbus类型的术语返回Dict of {String, Dict of {String, Variant}}a{sa{sv}}。我使用QtCreator和Qt4来构建我的应用程序。

我似乎从这本字典里找不出任何有用的信息。我无法提供MVE,因为它在很大程度上取决于NetworkManager和DBus以及Qt4是否安装在某人的系统上。

以下是我正在开发的从这个字符串词典和字符串及变体词典中获取信息的方法。当将它管道传输到qDebug():qDebug()<<reply时,我可以看到我想要的所有漂亮的数据。

void GetInfo()
{
//sysbus just means the system DBus.
QDBusInterface connSettings("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings/1", "org.freedesktop.NetworkManager.Settings.Connection", sysbus);
QDBusMessage reply = connections.call("GetSettings");
if(reply.type() == QDBusMessage::ReplyMessage)
{
//I have tried everything I can imagine here,
//QVariant g = reply.arguments().at(0).value<QVariant>(); did not work
//g.canConvert<QMap>(); returns false, in contrast to what KDE says.
//QDbusArgument g = query.arguments().at(0).value<QDBusArgument>();
//g.beginMap(); and such don't work
}
}

很难找到有关解析Dict类型的信息。我发现的唯一提供一些信息的来源是KDE。上面写着"DBus Dict类型应该映射到QMap,后面的例子……",谷歌上没有其他点击或例子。也许我错过了一些基本的数据库总线知识,但我被难住了。

我还检查了这个极好的答案:如何在Qt-DBus调用中提取QDBusMessage返回的数据?但我无法将其调整为解析dict。

有人知道如何到达最后一个嵌套的QVariant吗?

不幸的是,Qts-DBUS API并不总是最容易理解的,因此这里有一些技巧。基本上,我发现对我有效的是,你必须从回复中获得DBusArgument,而这正是为了获得实际数据而实际使用的。根据提取的内容,您可以覆盖.cpp文件中的operator<<operator>>(QDBusArgument的文档说明了如何执行此操作),也可以定义要提取的类型。另一个需要注意的重要事项是,QDBusReply::arguments()包含发送或接收的参数,具体取决于它是回复还是调用。

不管怎样,以下内容对我有效(尽管在Qt5中,但我希望它也能在Qt4中工作)

QDBusInterface connSettings("org.freedesktop.NetworkManager",
"/org/freedesktop/NetworkManager/Settings/1",
"org.freedesktop.NetworkManager.Settings.Connection",
QDBusConnection::systemBus() );
QDBusMessage reply = connSettings.call("GetSettings");
qDebug() << "Reply below:";
qDebug() << reply;
qDebug() << "Extracted: ";
// Extract the argument from the reply
// In this case, we know that we get data back from the method call,
// but a range check is good here as well(also to ensure that the 
// reply is a method reply, not an error)
const QDBusArgument &dbusArg = reply.arguments().at( 0 ).value<QDBusArgument>();
// The important part here: Define the structure type that we want to
// extract.  Since the DBus type is a{sa{sv}}, that corresponds to a 
// Map with a key of QString, which maps to another map of
// QString,QVariant
QMap<QString,QMap<QString,QVariant> > map;
dbusArg >> map;
qDebug() << "Map is: " << map;
// We're just printing out the data in a more user-friendly way here
for( QString outer_key : map.keys() ){
QMap<QString,QVariant> innerMap = map.value( outer_key );
qDebug() << "Key: " << outer_key;
for( QString inner_key : innerMap.keys() ){
qDebug() << "    " << inner_key << ":" << innerMap.value( inner_key );
}
}