表現(xiàn)方式 Qt中Signal Slot 4 種連接
表現(xiàn)方式 Qt 中Signal Slot 4 種連接是本文介紹的內(nèi)容,先來(lái)看內(nèi)容。signal/slot在底層會(huì)使用三種方式傳遞消息。參見(jiàn)QObject::connect()方法:
bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method, Qt::ConnectionType type = Qt::AutoCompatConnection )
最后一個(gè)參數(shù)是就是傳遞消息的方式了,有四個(gè)取值:
Qt::DirectConnection
When emitted, the signal is immediately delivered to the slot.
假設(shè)當(dāng)前有4個(gè)slot連接到QPushButton::clicked(bool),當(dāng)按鈕被按下時(shí),QT就把這4個(gè)slot按連接的時(shí)間順序調(diào)用一遍。顯然這種方式不能跨線程(傳遞消息)。
Qt::QueuedConnection
When emitted, the signal is queued until the event loop is able to deliver it to the slot.
假設(shè)當(dāng)前有4個(gè)slot連接到QPushButton::clicked(bool),當(dāng)按鈕被按下時(shí),QT就把這個(gè)signal包裝成一個(gè) QEvent,放到消息隊(duì)列里。QApplication::exec()或者線程的QThread::exec()會(huì)從消息隊(duì)列里取消息,然后調(diào)用 signal關(guān)聯(lián)的幾個(gè)slot。這種方式既可以在線程內(nèi)傳遞消息,也可以跨線程傳遞消息。
Qt::BlockingQueuedConnection
Same as QueuedConnection, except that the current thread blocks until the slot has been delivered. This connection type should only be used for receivers in a different thread. Note that misuse of this type can lead to dead locks in your application.
與Qt::QueuedConnection類似,但是會(huì)阻塞等到關(guān)聯(lián)的 slot 都被執(zhí)行。這里出現(xiàn)了阻塞這個(gè)詞,說(shuō)明它是專門用來(lái)多線程間傳遞消息的。
Qt::AutoConnection
If the signal is emitted from the thread in which the receiving object lives, the slot is invoked directly, as with Qt::DirectConnection; otherwise the signal is queued, as with Qt::QueuedConnection.
這種連接類型根據(jù)signal和slot是否在同一個(gè)線程里自動(dòng)選擇Qt::DirectConnection或Qt::QueuedConnection
這樣看來(lái),第一種類型的效率肯定比第二種高,畢竟第二種方式需要將消息存儲(chǔ)到隊(duì)列,而且可能會(huì)涉及到大對(duì)象的復(fù)制(考慮sig_produced(BigObject bo),bo需要復(fù)制到隊(duì)列里)。
與wxWidget、MFC的效率比較
wxWidget沒(méi)用過(guò),了解過(guò)MFC。我覺(jué)得MFC的消息隊(duì)列是比較簡(jiǎn)單的,一般只是傳遞long數(shù)值、HANDLE、指針,效率上應(yīng)該會(huì)比QT的隊(duì)列方式高,然而QT的靈活性是MFC沒(méi)辦法比擬的,我還是比較喜歡QT這樣的。
小結(jié):表現(xiàn)方式 Qt 中Signal Slot 4 種連接的內(nèi)容介紹完了,希望本文對(duì)你有所幫助。