Qt訊號與槽連線

2021-08-15 16:22:43 字數 2968 閱讀 6379

connect(pointer1, pointer2, pointer3, pointer4);

pointer1:指向傳送訊號的物件的指標

pointer2:傳送訊號的物件所對應的類的成員函式的指標

pointer3:接收訊號的物件的指標

pointer4:接收訊號的物件所對應物件的槽函式指標

總結下來就是:

訊號:只需宣告無需實現,且沒有返回值;

槽函式:qt5類中任意成員函式,靜態函式,全域性函式,lambda表示式,槽函式可以有返回值,但只有在作為普通函式呼叫時才能接受,訊號觸發呼叫時無法接受;

訊號與槽使用函式指標形式傳入時格式必須是類名::成員函式名(訊號或槽);

訊號和槽的引數列表順序必須一致;

訊號和槽的引數個數可以不一致,但要滿足訊號的引數個數大於等於槽函式引數個數,槽函式會忽略訊號傳遞的多餘引數。

例如:mainwidget.h檔案:

class mainwidget : public qwidget

;

mainwidget.cpp檔案:

mainwidget::mainwidget(qwidget *parent) : qwidget(parent), pushbutton(new qpushbutton(this))

void mainwidget::switchwinslot()

乙個訊號可以連線多個槽,槽函式的執行順序是隨機的,無法控制

多個訊號可以連線乙個槽

乙個訊號可以連線另乙個訊號(這兩個訊號可以是不同物件的訊號)這裡對第三點舉例 

訊號和槽連線成功後,可以斷開連線disconnect

subwidget.h檔案:

class subwidget : public qwidget

;

subwidget.cpp檔案:

subwidget::subwidget(qwidget *parent) : qwidget(parent)

此例子是子視窗產生clicked訊號時會同時產生自定義的switchwin訊號,用來實現主視窗與子視窗之間的切換

訊號和槽函式可以進行過載,利用qt5格式連線過載的訊號和槽時,應該使用函式指標變數對過載訊號或槽進行區分

subwidget.h檔案:

class subwidget : public qwidget

;

subwidget.cpp檔案:

subwidget::subwidget(qwidget *parent) : qwidget(parent)

上述函式指標涉及到類成員函式的函式指標,詳見:

這是我們對subclass的switchwin進行了過載,所以也要對mainwidget.cpp中connect連線switchwin訊號的**進行修改,這裡我們用另一種方法,使用static_cast<>運算子對函式指標進行型別轉換來區別switchwin的過載;

mainwidget.cpp修改如下:

#include "mainwidget.h"

#include #include "subwidget.h"

mainwidget::mainwidget(qwidget *parent) : qwidget(parent), pushbutton(new qpushbutton(this))

void mainwidget::switchwinslot()

上述涉及到的函式指標和過載函式的結合使用可以參考:

也可以利用qt4中的訊號與槽連線機制對過載進行區分,但不推薦使用,因為qt4使用巨集定義會將函式名轉化成字串,所以並不會提供編譯的錯誤檢查,並且,slot()巨集要求所有的槽函式必須使用***(public) slots:關鍵字進行修飾,qt4格式如下:

connect(sender, signal(signal), receiver, slot(slot));

connect函式還可以使用lambda表示式,在pro檔案中加入config+=c++11,上述connect語句可以換成

connect(pushbutton, &qpushbutton::clicked,

[=]());

或者

connect(pushbutton, &qpushbutton::clicked,

[this]());

關於lambda表示式的用法詳見:

connect()函式可以自己設定第5個引數:

qmetaobject::connection qobject::connect(const qobject *sender, const char *signal, const qobject *receiver, const char *method, 

qt::connectiontype type = qt::autoconnection)

最後乙個引數取值及其含義如下:

qt::autoconnection (預設)

qt::directconnection

qt::queuedconnection

qt::blockingqueuedconnection

qt::uniqueconnection

qt::autoconnection:如果訊號傳送者和接受者在同乙個執行緒,則選用qt::directconnection,如果不在同乙個執行緒,則使用qt::queuedconnection做引數;

qt::uniqueconnection:這個標識可以和其他任何標示聯合使用(用按位或操作符),它保證乙個訊號和乙個槽之間只能呼叫一次connect()函式,如果連線已經存在,則呼叫失敗。

QT 訊號與槽有連線 槽未響應

日常錯誤記錄 在連線訊號和槽時 訊號和槽的引數要一一對應,名字空間也要對應 錯誤 connect p topshapematchthread,signal send result halconcpp hobject,qstring,bool this,slot on getimagefromdotg...

QT類之間訊號與槽連線

qt中使用訊號與槽機制來傳遞訊號,實現按鈕響應,選單欄響應等操作。與先例項化類的物件,再呼叫類的成員函式,實現了類似的功能。connect ui action open,signal triggered this,slot showopenfiledlg 2 類之間槽的連線 類間訊號與槽連線,但是沒...

QT訊號與槽的連線方式

一.qt autoconnection qt autoconnection表示系統自動選擇相應的連線方式,如果訊號與槽在同一執行緒,就採用qt directconnection,如果訊號與槽不在同一執行緒,將採用qt queuedconnection的連線方式。二.qt directconnecti...