您的位置:首页 > 编程语言 > Qt开发

Qt信号与槽的参数传递原理

2015-08-03 20:39 746 查看
我们这里不讲信号和槽的概念,请各自网络上搜索。但是很多人可能没想过,emit一个信号后,信号的参数是如何传递到槽里面。当然,支持信号和槽,对象就必须要有元系统,通过元系统来传递参数。不过这里有两个问题需要考虑到,否则参数是无法正确传递的。

1,如果传递的是自定义数据类型

对于自定义数据类型,需要声明该数据类型为元数据,qRegisterMetaType

2,我们知道,在connect信号和槽的时候,可以指定是连接类型,比如,direct和queue,当然还有其他的。如果是采用队列方式,参数是会被放在队列的。那么这里就涉及到数据的拷贝,于是我们需要实现自定义数据类型的拷贝函数,否则数据将无法正确地拷贝到队列,也就无法正确的传递了。

个人觉得这两点是必须要知道的,否则信号与槽就无法正确的使用。不过我这里并没有详细描述。之后有时间再补充。谢谢

附Qt文档:

enum Qt::ConnectionType

This enum describes the types of connection that can be used between signals and slots. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time.

Constant Value
Description

Qt::AutoConnection 0
(Default) If the receiver lives in the thread that emits the signal, Qt::DirectConnection is used. Otherwise, Qt::QueuedConnection is used. The connection type is determined when the signal is emitted.

Qt::DirectConnection 1
The slot is invoked immediately when the signal is emitted. The slot is executed in the signalling thread.

Qt::QueuedConnection 2
The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.

Qt::BlockingQueuedConnection 3
Same as Qt::QueuedConnection, except that the signalling thread blocks until the slot returns. This connection must not be used if the receiver lives in the signalling thread, or else the application will deadlock.

Qt::UniqueConnection 0x80
This is a flag that can be combined with any one of the above connection types, using a bitwise OR. When Qt::UniqueConnection is set, QObject::connect() will fail if the connection already exists (i.e. if the same signal is already connected to the same
slot for the same pair of objects). This flag was introduced in Qt 4.6.

With queued connections, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message:

QObject::connect: Cannot queue arguments of type 'MyType'

Call qRegisterMetaType() to register the data type before you establish the connection.

When using signals and slots with multiple threads, see Signals and Slots Across Threads.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: