本文主要是對C++ GUI Programming with Qt4一書 Signals and Slots in Depth 部分的翻譯
信號與插槽機制是Qt編程的基礎.它可以綁定對象而不需要對象之間彼此了解。
槽類似于c++中的成員函數他可以是虛擬的,可重載的,私有的,公開的,受保護的。
不同點式槽可以鏈接到信號。通過這種方式可以在每次信號發射的的時候做到調用槽函數
connect()語句是這樣的
connect(sender, SIGNAL(signal), receiver, SLOT(slot));
在這里sender和receiver是指向信號對象和槽對象的指針。宏SIGNAL()和SLOTS()負責轉換他們的參數到字符串。
當然一個信號可以連接到多個槽(似乎都是這樣的)
connect(slider, SIGNAL(valueChanged(int)),
spinBox, SLOT(setValue(int)));
connect(slider, SIGNAL(valueChanged(int)),
this, SLOT(updateStatusBarIndicator(int)));
同樣多個信號可以連接到單個槽
例如:
connect(lcd, SIGNAL(overflow()),
this, SLOT(handleMathError()));
connect(calculator, SIGNAL(divisionByZero()),
this, SLOT(handleMathError()));
除此之外信號可以連接到其他信號(見過的其他插槽系統似乎不大可以?)
connect(lineEdit, SIGNAL(textChanged(const QString &)),
this, SIGNAL(updateRecord(const QString &)));
需要指出的是信號信號鏈接和信號插槽連接時不同的
既然信號和插槽可以連接那么他們應該可以斷開,如下:
disconnect(lcd, SIGNAL(overflow()),
this, SLOT(handleMathError()));
一個簡單的例子:
class Employee : public QObject
{
Q_OBJECT
public:
Employee() { mySalary = 0; }
int salary() const { return mySalary; }
public slots:
void setSalary(int newSalary);
signals:
void salaryChanged(int newSalary);
private:
int mySalary;
};
void Employee::setSalary(int newSalary)
{
if (newSalary != mySalary) {
mySalary = newSalary;
emit salaryChanged(mySalary);
}
}
說明
關鍵字 public slots:和signals
他們用于修飾插槽函數和信號函數
至于信號的反射通過關鍵字 emit來實現
通過本文基本掌握了QT的信號插槽機制