在捕获全部回调中识别来自QDBusPendingCallWatcher的原始调用



我想使用Qt的QDBusPendingCallWatcher来跟踪一些D-Bus调用的响应。我可以进行几种不同的 D-Bus 调用,但我希望对所有调用都有一个回调。

问题是,当返回值准备就绪时,QDBusPendingCallWatcher发出的finished信号只有一个指向QDBusPendingCallWatcher本身的指针,并且我找不到获取原始QDBusMessage(其中包含调用的方法(的方法的方法。

深入研究Qt的源代码,您可以看到调用asyncCall会创建QDBusMessage,而又会传递给正在使用的QDBusConnection,但遗憾的是,这些信息是使用QDBusPendingCallPrivate中的pimpl模式存储的,并且似乎无法从客户端代码中恢复。

TL;DR:是否有可能从QDBusPendingCallWatcher::finished信号触发的插槽内知道异步D-Bus调用的方法名称?

正如您所发现的,似乎没有办法取回原始消息。 但是,我可以看到至少两种解决方法。 由于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;
}

相关内容

  • 没有找到相关文章

最新更新