【问题标题】:QtDBus Simply Example With PowerManagerQtDBus 使用 PowerManager 的简单示例
【发布时间】:2015-08-26 12:38:59
【问题描述】:

我正在尝试使用 QtDbus 与系统中PowerManager 提供的接口进行通信。我的目标很简单。我将编写代码,使用 DBus 接口使我的系统休眠

所以,我安装了 d-feet 应用程序来查看我的系统上有哪些 interfaces DBus 可用,以及我看到了什么:

正如我们所见,我有一些接口和方法可供我选择。我的选择是 Hibernate(),来自界面 org.freedesktop.PowerManagment

在这个目标中,我准备了一些非常简单的代码来只了解机制。我当然使用了 Qt 库:

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtDBus/QtDBus>
#include <QDBusInterface>
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    if (!QDBusConnection::sessionBus().isConnected()) {
        fprintf(stderr, "Cannot connect to the D-Bus session bus.\n"
                "To start it, run:\n"
                "\teval `dbus-launch --auto-syntax`\n");
        return 1;
    }
    QDBusInterface iface("org.freedesktop.PowerManagement" ,"/" , "" , QDBusConnection::sessionBus());
    if(iface.isValid())
    {
        qDebug() << "Is good";
        QDBusReply<QString> reply = iface.call("Methods" , "Hibernate");
        if(reply.isValid())
        {
            qDebug() << "Hibernate by by " <<  qPrintable(reply.value());
        }

        qDebug() << "some error " <<  qPrintable(reply.error().message());

    }

    return 0;
}

不幸的是,我的终端出现错误:

不错
接口“(null)”上带有签名“s”的一些错误方法“方法”不存在

那么请告诉我这段代码有什么问题?我确定我忘记了函数 QDBusInterface::call() 中的一些参数,但是什么?

【问题讨论】:

    标签: qt qdbus


    【解决方案1】:

    创建接口时,您必须指定正确的interface, path, service。这就是为什么你的iface 对象应该这样创建:

    QDBusInterface iface("org.freedesktop.PowerManagement",  // from list on left
                         "/org/freedesktop/PowerManagement", // from first line of screenshot
                         "org.freedesktop.PowerManagement",  // from above Methods
                         QDBusConnection::sessionBus());
    

    此外,在调用方法时,您需要使用它的名称和参数(如果有):

    iface.call("Hibernate");
    

    Hibernate() 没有输出参数,所以你必须使用QDBusReply&lt;void&gt; 并且不能检查.value()

    QDBusReply<void> reply = iface.call("Hibernate");
    if(reply.isValid())
    {
        // reply.value() is not valid here
    }
    

    【讨论】:

    • 谢谢。我想补充一些。如果 answer 不仅是一个字符串,而且类似于 JSON 格式,我们也可以使用此代码QDBusMessage reply = iface.call("GetConfig"); qDebug() &lt;&lt; reply;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 2019-08-02
    • 2016-03-02
    • 2012-06-09
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多