原文地址 :http://devbean.blog.51cto.com/448512/199461 写的超级好的专栏。
信号槽机制
1.作用
: 通过信号槽,能够使Qt各组件在不知道对方的情形下能够相互通讯。这就将类之间的关系做了最大程度的解耦。槽函数可以和一个信号相连接,当这个信号发生时,它可以被自动调用。
信号槽机制的格式
connect(sender, SIGNAL(signal), receiver, SLOT(slot));
sender和receiver都是QObject类型的,singal和slot都是没有参数名称的函数签名。SINGAL()和SLOT()宏用于把参数转换成字符串。
2.槽机制更多格式
(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)槽可以被取消链接
disconnect(lcd, SIGNAL(overflow()),this, SLOT(handleMathError()));
3.参数
(1)为了正确的连接信号槽,信号和槽的参数个数、类型以及出现的顺序都必须相同
connect(ftp, SIGNAL(rawCommandReply(int, const QString &)),this, SLOT(processReply(int, const QString &)));
(2)如果信号的参数多于槽的参数,那么这个参数之后的那些参数都会被忽略掉。
connect(ftp, SIGNAL(rawCommandReply(int, const QString &)), this, SLOT(checkErrorCode(int)));
这里,const QString &这个参数就会被槽忽略掉
4.信号槽机制的使用
connect()函数其实是在QObject中实现的,并不局限于GUI,因此,只要我们继承QObject类,就可以使用信号槽机制了.
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);
}
}
if判断用于避免循环递归。