热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

IntroductiontoQtDBusclass

from: http:doc.qt.ioqt-5qtdbus-index.html参考: http:blog.51cto.com92919272118468声明与链接#includ

from: http://doc.qt.io/qt-5/qtdbus-index.html

参考: http://blog.51cto.com/9291927/2118468

声明与链接

#include

如使用qmake构建程序,需要在工程文件中增加下列代码来链接QtDBus库:

QT += qdbus

QtDBus类型系统

  • Primitive Types
  • Compound Types
  • Extending the Type System
  • The Type System in Use

QtDBus常用类

QDBusMessage

The QDBusMessage class represents one message sent or received over the D-Bus bus.

This object can represent any of the four different types of messages (MessageType) that can occur on the bus:

  • MethodCallMessage
  • SignalMessage
  • ReplyMessage
  • ErrorMessage

Objects of this type are created with the static createError(), createMethodCall() and createSignal() functions. Use the QDBusConnection::send() function to send the messages.

QDBusConnection

The QDBusConnection class represents a connection to the D-Bus bus daemon.

This class is the initial point in a D-Bus session. Using it, you can get access to remote objects, interfaces; connect remote signals to your object‘s slots; register objects, etc.

  • D-Bus connections are created using the connectToBus() function, which opens a connection to the server daemon and does the initial handshaking, associating that connection with a name.
  • The connection is then torn down using the disconnectFromBus() function.
  • As a convenience for the two most common connection types, the sessionBus() and systemBus() functions return open connections to the session server daemon and the system server daemon, respectively.
  • D-Bus also supports peer-to-peer connections, without the need for a bus server daemon. Using this facility, two applications can talk to each other and exchange messages. This can be achieved by passing an address to connectToBus() function, which was opened by another D-Bus application using QDBusServer.
  • connectToPeer() & disconnectFromPeer()
  • localMachineId(): Returns the local machine ID as known to the D-Bus system. Each node or host that runs D-Bus has a unique identifier that can be used to distinguish it from other hosts if they are sharing resources like the filesystem.
  • call() & asyncCall()
  • registerObject(): Registers the object object at path.
  • registerService(): Attempts to register the serviceName on the D-Bus server.

QDBusConnectionInterface

The QDBusConnectionInterface class provides access to the D-Bus bus daemon service.

The D-Bus bus server daemon provides one special interface org.freedesktop.DBus that allows clients to access certain properties of the bus, such as the current list of clients connected. The QDBusConnectionInterface class provides access to that interface.

  • register and unregister service names on the bus using the registerService() and unregisterService() functions
  • query about existing names using the isServiceRegistered(), registeredServiceNames() and serviceOwner() functions
  • receive notification that a client has registered or de-registered through the serviceRegistered(), serviceUnregistered() and serviceOwnerChanged() signals.

QDBusInterface

The QDBusInterface class is a proxy for interfaces on remote objects.

QDBusInterface is a generic accessor class that is used to place calls to remote objects, connect to signals exported by remote objects and get/set the value of remote properties. This class is useful for dynamic access to remote objects: that is, when you do not have a generated code that represents the remote interface.

  • Calls are usually placed by using the call() function, which constructs the message, sends it over the bus, waits for the reply and decodes the reply. Signals are connected to by using the normal QObject::connect() function. Finally, properties are accessed using the QObject::property() and QObject::setProperty() functions.
QDBusInterface remoteApp( "com.example.Calculator", "/Calculator/Operations",
                          "org.mathematics.RPNCalculator" );
remoteApp.call( "PushOperand", 2 );
remoteApp.call( "PushOperand", 2 );
remoteApp.call( "ExecuteOperation", "+" );
QDBusReply<int> reply = remoteApp.call( "PopOperand" );

if ( reply.isValid() )
    printf( "%d", reply.value() );          // prints 4

QDBusAbstractInterface

The QDBusAbstractInterface  class is the base class for all D-Bus interfaces in the Qt D-Bus binding, allowing access to remote interfaces.

Generated-code classes also derive from QDBusAbstractInterface, all methods described here are also valid for generated-code classes. In addition to those described here, generated-code classes provide member functions for the remote methods, which allow for compile-time checking of the correct parameters and return values, as well as property type-matching and signal parameter-matching.

  • call (const QString &method, const QVariant &arg1 = QVariant() ... ) -> return QDBusMessage
  • asyncCall (const QString &method, const QVariant &arg1 = QVariant() ... ) -> return QDBusPendingCall
QString value = retrieveValue();
QDBusMessage reply;

QDBusReply<int> api = interface->call(QLatin1String("GetAPIVersion"));
if (api >= 14)
  reply = interface->call(QLatin1String("ProcessWorkUnicode"), value);
else
  reply = interface->call(QLatin1String("ProcessWork"), QLatin1String("UTF-8"), value.toUtf8());
QString value = retrieveValue();
QDBusPendingCall pcall = interface->asyncCall(QLatin1String("Process"), value);

QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, this);

QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
                 this, SLOT(callFinishedSlot(QDBusPendingCallWatcher*)));

QDBusReply

The QDBusReply class stores the reply for a method call to a remote object.

A QDBusReply object is a subset of the QDBusMessage object that represents a method call‘s reply. It contains only the first output argument or the error code and is used by QDBusInterface-derived classes to allow returning the error code as the function‘s return argument.

QDBusReply objects are used for remote calls that have no output arguments or return values (i.e., they have a "void" return type). Use the isValid() function to test if the reply succeeded.

QDBusReply reply = interface->call("RemoteMethod");
if (reply.isValid())
    // use the returned value
    useValue(reply.value());
else
    // call failed. Show an error condition.
    showError(reply.error());

If the remote method call cannot fail, you can skip the error checking:

QString reply = interface->call("RemoteMethod");

However, if it does fail under those conditions, the value returned by QDBusReply::value() is a default-constructed value. It may be indistinguishable from a valid return value.

QDBusArgument

The QDBusArgument  class is used to marshall and demarshall D-Bus arguments.

The class is used to send arguments over D-Bus to remote applications and to receive them back. D-Bus offers an extensible type system, based on a few primitive types and associations of them. See the Qt D-Bus Type System page for more information on the type system.

QDBusArgument is the central class in the Qt D-Bus type system, providing functions to marshall and demarshall the primitive types. The compound types are then created by association of one or more of the primitive types in arrays, dictionaries or structures.

struct MyStructure
{
    int count;
    QString name;
};
Q_DECLARE_METATYPE(MyStructure)

// Marshall the MyStructure data into a D-Bus argument
QDBusArgument &operator<<(QDBusArgument &argument, const MyStructure &mystruct)
{
    argument.beginStructure();
    argument < mystruct.name;
    argument.endStructure();
    return argument;
}

// Retrieve the MyStructure data from the D-Bus argument
const QDBusArgument &operator>>(const QDBusArgument &argument, MyStructure &mystruct)
{
    argument.beginStructure();
    argument >> mystruct.count >> mystruct.name;
    argument.endStructure();
    return argument;
}

The type has to be registered with qDBusRegisterMetaType() before it can be used with QDBusArgument. Therefore, somewhere in your program, you should add the following code:

qDBusRegisterMetaType<MyStructure>();

Once registered, a type can be used in outgoing method calls (placed with QDBusAbstractInterface::call() ), signal emissions from registered objects or in incoming calls from remote applications.

It is important to note that the operator<> streaming functions must always produce the same number of entries in case of structures, both in reading and in writing (marshalling and demarshalling), otherwise calls and signals may start to silently fail.

The following example illustrates this wrong usage in context of a class that may contain invalid data:

//bad code
    // Wrongly marshall the MyTime data into a D-Bus argument
    QDBusArgument &operator<<(QDBusArgument &argument, const MyTime &mytime)
    {
        argument.beginStructure();
        if (mytime.isValid)
            argument <<true << mytime.hour
                     < mytime.second;
        else
            argument <<false;
        argument.endStructure();
        return argument;
    }

In this example, both the operator<> functions may produce a different number of reads/writes. This can confuse the Qt D-Bus type system and should be avoided.

QDBusAbstractAdaptor

The QDBusAbstractAdaptor class is the base class of D-Bus adaptor classes.

The QDBusAbstractAdaptor class is the starting point for all objects intending to provide interfaces to the external world using D-Bus. This is accomplished by attaching a one or more classes derived from QDBusAbstractAdaptor to a normal QObject and then registering that QObject with QDBusConnection::registerObject. QDBusAbstractAdaptor objects are intended to be light-weight wrappers, mostly just relaying calls into the real object (its parent) and the signals from it.

Each QDBusAbstractAdaptor-derived class should define the D-Bus interface it is implementing using the Q_CLASSINFO macro in the class definition. Note that only one interface can be exposed in this way.

QDBusAbstractAdaptor uses the standard QObject mechanism of signals, slots and properties to determine what signals, methods and properties to export to the bus. Any signal emitted by QDBusAbstractAdaptor-derived classes will be automatically be relayed through any D-Bus connections the object is registered on.

Classes derived from QDBusAbstractAdaptor must be created on the heap using the new operator and must not be deleted by the user (they will be deleted automatically when the object they are connected to is also deleted).

QDBusPendingCall

The QDBusPendingCall class refers to one pending asynchronous call.

In most programs, the QDBusPendingCall class will not be used directly. It can be safely replaced with the template-based QDBusPendingReply, in order to access the contents of the reply or wait for it to be complete.

The QDBusPendingCallWatcher class allows one to connect to a signal that will indicate when the reply has arrived or if the call has timed out. It also provides the QDBusPendingCallWatcher::waitForFinished() method which will suspend the execution of the program until the reply has arrived.

Note: If you create a copy of a QDBusPendingCall object, all information will be shared among the many copies. Therefore, QDBusPendingCall is an explicitly-shared object and does not provide a method of detaching the copies (since they refer to the same pending call)

QDBusPendingReply

The QDBusPendingReply class contains the reply to an asynchronous method call.

The QDBusPendingReply is a template class with up to 8 template parameters. Those parameters are the types that will be used to extract the contents of the reply‘s data.

This class is similar in functionality to QDBusReply, but with two important differences:

  • QDBusReply accepts exactly one return type, whereas QDBusPendingReply can have from 1 to 8 types
  • QDBusReply only works on already completed replies, whereas QDBusPendingReply allows one to wait for replies from pending calls
QDBusPendingReply reply = interface->asyncCall("RemoteMethod");
reply.waitForFinished();
if (reply.isError())
    // call failed. Show an error condition.
    showError(reply.error());
else
    // use the returned value
    useValue(reply.value());

For method calls that have more than one output argument:

QDBusPendingReply<bool, QString> reply = interface->asyncCall("RemoteMethod");
reply.waitForFinished();
if (!reply.isError()) {
    if (reply.argumentAt<0>())
        showSuccess(reply.argumentAt<1>());
    else
        showFailure(reply.argumentAt<1>());
}

QDBusPendingCallWatcher

The QDBusPendingCallWatcher class provides a convenient way for waiting for asynchronous replies.

The QDBusPendingCallWatcher provides the finished() signal that will be emitted when a reply arrives.

It is usually used like the following example:

QDBusPendingCall async = iface->asyncCall("RemoteMethod", value1, value2);
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(async, this);

QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
                 this, SLOT(callFinishedSlot(QDBusPendingCallWatcher*)));

Note that it is not necessary to keep the original QDBusPendingCall object around since QDBusPendingCallWatcher inherits from that class too.

The slot connected to by the above code could be something similar to the following:

void MyClass::callFinishedSlot(QDBusPendingCallWatcher *call)
{
    QDBusPendingReply reply = *call;
    if (reply.isError()) {
        showError();
    } else {
        QString text = reply.argumentAt<0>();
        QByteArray data = reply.argumentAt<1>();
        showReply(text, data);
    }
    call->deleteLater();
}

Note the use of QDBusPendingReply to validate the argument types in the reply. If the reply did not contain exactly two arguments (one string and one QByteArray), QDBusPendingReply::isError() will return true.

QDBusServer

The QDBusServer class provides peer-to-peer communication between processes on the same computer.

QDBusServiceWatcher

The QDBusServiceWatcher class allows the user to watch for a bus service change.

A QDBusServiceWatcher object can be used to notify the application about an ownership change of a service name on the bus. It has three watch modes:

  • Watching for service registration only.
  • Watching for service unregistration only.
  • Watching for any kind of service ownership change (the default mode).

Besides being created or deleted, services may change owners without a unregister/register operation happening. So the serviceRegistered() and serviceUnregistered() signals may not be emitted if that happens.

This class is more efficient than using the QDBusConnectionInterface::serviceOwnerChanged() signal because it allows one to receive only the signals for which the class is interested in.

QDBusVariant

The QDBusVariant class enables the programmer to identify the variant type provided by the D-Bus typesystem.

Qt D-Bus XML compiler (qdbusxml2cpp)

The Qt D-Bus XML compiler is a tool that can be used to parse interface descriptions and produce static code representing those interfaces, which can then be used to make calls to remote objects or implement said interfaces.

qdbusxml2cpp has two modes of operation, that correspond to the two possible outputs it can produce: the interface (proxy) class or the adaptor class. The latter consists of both a C++ header and a source file, which are meant to be edited and adapted to your needs.

The qdbusxml2cpp tool is not meant to be run every time you compile your application. Instead, it‘s meant to be used when developing the code or when the interface changes.

The adaptor classes generated by qdbusxml2cpp are just a skeleton that must be completed. It generates, by default, calls to slots with the same name on the object the adaptor is attached to. However, you may modify those slots or the property accessor functions to suit your needs.

Introduction to QtDBus class


推荐阅读
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 本文介绍了通过ABAP开发往外网发邮件的需求,并提供了配置和代码整理的资料。其中包括了配置SAP邮件服务器的步骤和ABAP写发送邮件代码的过程。通过RZ10配置参数和icm/server_port_1的设定,可以实现向Sap User和外部邮件发送邮件的功能。希望对需要的开发人员有帮助。摘要长度:184字。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • Voicewo在线语音识别转换jQuery插件的特点和示例
    本文介绍了一款名为Voicewo的在线语音识别转换jQuery插件,该插件具有快速、架构、风格、扩展和兼容等特点,适合在互联网应用中使用。同时还提供了一个快速示例供开发人员参考。 ... [详细]
author-avatar
美竹
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有