訊號(signal)和槽(slot)
- 類似於windows中的訊息和訊息響應
- 都是通過C++類成員函數實現的
- 訊號和槽是通過串連實現相互關聯的
- 包含訊號或槽的類必須從QObject繼承
訊號(signal)和槽(slot)——聲明
class Employee : public QObject{Q_OBJECTpublic:Employee();int salary() const;public slots:void setSalary(int newSalary);signals:void salaryChanged(int newSalary);private:int mySalary;};emit salaryChanged(50);訊號(signal)和槽(slot)——串連
connect(sender, SIGNAL(signal),receiver, SLOT(slot));
1.一個訊號可以串連多個槽,這些槽被調用的順序是隨機的connect(slider, SIGNAL(valueChanged(int)),spinBox, SLOT(setValue(int)));connect(slider, SIGNAL(valueChanged(int)),this, SLOT(updateStatusBarIndicator(int)));2.一個槽可以串連多個訊號,每個訊號都可以觸發該槽connect(lcd, SIGNAL(overflow()),this, SLOT(handleMathError()));connect(calculator, SIGNAL(divisionByZero()),this, SLOT(handleMathError()));3.訊號之間可以相互串連,相互串連的訊號會相互觸發connect(lineEdit,SIGNAL(textChanged(const QString &)),this,SIGNAL(updateRecord(const QString &)));4.槽和槽之間不能相互串連
訊號和訊號、訊號和槽之間在運行時串連,而且可以在運行時取消串連;Qt會在適當的時候自動取消串連,所以一般沒有必要手動取消串連connect(lcd, SIGNAL(overflow()),this, SLOT(handleMathError()));disconnect(lcd, SIGNAL(overflow()),this, SLOT(handleMathError()));
訊號和槽需要具有相同的參數列表;如果訊號的參數比槽多,那麼多餘的參數會被忽略;如果參數列表不匹配,Qt會產生執行階段錯誤資訊connect(ftp, SIGNAL(rawCommandReply(int, const QString&)),this, SLOT(processReply(int, const QString&)));connect(ftp, SIGNAL(rawCommandReply(int, const QString&)),this, SLOT(checkErrorCode(int)));
參考:QT 的訊號與槽機制介紹