Qt信号和槽连接方式的选择
?
看了下Qt的幫助文檔,發(fā)現(xiàn)connect函數(shù)最后還有一個(gè)缺省參數(shù).
connect函數(shù)原型是這樣的:
QMetaObject::Connection QObject::connect(const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoConnection)
最后的ConnectionType是一個(gè)缺省的參數(shù),默認(rèn)為自動(dòng)連接方式,我們來(lái)看一下這個(gè)參數(shù)有哪些值
?
Qt supports these signal-slot connection types:
Auto Connection (default)?If the signal is emitted in the thread which the receiving object has affinity then the behavior is the same as the Direct Connection. Otherwise, the behavior is the same as the Queued Connection."
Direct Connection?The slot is invoked immediately, when the signal is emitted. The slot is executed in the emitter's thread, which is not necessarily the receiver's thread.
Queued Connection?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.
Blocking Queued Connection?The slot is invoked as for the Queued Connection, except the current thread blocks until the slot returns.
Note: Using this type to connect objects in the same thread will cause deadlock.
Unique Connection?The behavior is the same as the Auto Connection, but the connection is made only if it does not duplicate an existing connection. i.e., if the same signal is already connected to the same slot for the same pair of objects, then the connection is not made and connect() returns false
可以看出一共是5個(gè)值:自動(dòng)、直接、隊(duì)列、阻塞隊(duì)列、唯一。
我們先看下 直接和隊(duì)列。
直接連接的大概意思是:信號(hào)一旦發(fā)射,槽立即執(zhí)行,并且槽是在信號(hào)發(fā)射的線程中執(zhí)行的。
隊(duì)列連接的大概意思是:信號(hào)發(fā)射后當(dāng)事件循環(huán)返回到接收線程時(shí)槽函數(shù)就執(zhí)行了,也就是說(shuō)這種連接方式不是立即觸發(fā)槽函數(shù)的,而是要排隊(duì)等的,并且是在槽函數(shù)的線程中執(zhí)行。
?
再來(lái)看看 自動(dòng)和阻塞隊(duì)列方式
自動(dòng)連接的大概意思是:信號(hào)發(fā)射對(duì)象如果和槽的執(zhí)行對(duì)象在同一個(gè)線程,那么將是直連方式,否則就是隊(duì)列方式。
阻塞隊(duì)列方式:在槽函數(shù)返回之前槽函數(shù)所在的線程都是阻塞的。
?
唯一方式:和直連相同,但是只能一對(duì)一連接。
Qt幫助文檔中提醒到:Be aware that using direct connections when the sender and receiver live in different threads is unsafe if an event loop is running in the receiver's thread, for the same reason that calling any function on an object living in another thread is unsafe.
即跨線程調(diào)QObject對(duì)象是不安全的。
Call qRegisterMetaType() to register the data type before you establish the connection。
另外信號(hào)槽的參數(shù)必須是注冊(cè)的MetaType,所以當(dāng)你使用自定義的類(lèi)型或者 沒(méi)有注冊(cè)的類(lèi)型,都要調(diào)用qRegisterMetaType()進(jìn)行注冊(cè),因?yàn)镼t需要保存你的參數(shù)。
總結(jié)
以上是生活随笔為你收集整理的Qt信号和槽连接方式的选择的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Qt中子线程创建运行时候出现QObjec
- 下一篇: QT多线程run函数不能使用信号与槽