我想使用Qt' QDBusPendingCallWatcher
来跟踪某些D-Bus呼叫的响应。我可以进行几种不同的D-Bus呼叫,但我希望对所有这些呼叫都进行一次回调。
问题是当返回值准备好时finished
发出的QDBusPendingCallWatcher
信号只有一个指向QDBusPendingCallWatcher
本身的指针,而我发现无法获取原始QDBusMessage
{1}}(包含被调用的方法)。
深入研究Qt的源代码,您可以看到调用asyncCall
会创建QDBusMessage
,而QDBusConnection
又传递给正在使用的QDBusPendingCallPrivate
,但遗憾的是信息使用QDBusPendingCallWatcher::finished
中的pimpl模式存储,似乎无法从客户端代码中恢复。
TL; DR:是否可以从visibilty: visible
信号触发的插槽中知道异步D-Bus呼叫的方法名称?
答案 0 :(得分:1)
正如您所知,似乎无法获得原始消息。但是,我能看到至少两种解决方法。由于QDbusPendingCallWatcher
继承自QObject
,因此您可以在观察程序上设置一个属性,以保留方法调用的名称。或者,您可以使用lambda函数向回调添加更多信息(例如方法名称)。
DBusCaller::DBusCaller(QObject *parent) : QObject(parent)
{
QDBusInterface connSettings("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings/1",
"org.freedesktop.NetworkManager.Settings.Connection",
QDBusConnection::systemBus() );
//Method 1: set a property on the object
{
QDBusPendingCall pending = connSettings.asyncCall( "GetSettings" );
QDBusPendingCallWatcher* watch = new QDBusPendingCallWatcher( pending );
watch->setProperty( "method", "GetSettings" );
connect( watch, &QDBusPendingCallWatcher::finished,
this, &DBusCaller::callFinished );
}
//Method 2: use a lambda to add more information to our callback
{
QString methodName = "GetSettings";
QDBusPendingCall pending = connSettings.asyncCall( methodName );
QDBusPendingCallWatcher* watch = new QDBusPendingCallWatcher( pending );
connect( watch, &QDBusPendingCallWatcher::finished,
this, [=](QDBusPendingCallWatcher* reply) { callFinishedString( methodName, reply ); });
}
}
void DBusCaller::callFinished(QDBusPendingCallWatcher* pending){
pending->deleteLater();
qDebug() << "Pending finished. Method: " << pending->property( "method" );
}
void DBusCaller::callFinishedString(QString methodName,
QDBusPendingCallWatcher *watch){
watch->deleteLater();
qDebug() << "Pending finsihed. Method: " << methodName;
}