QT的 signal & slot机制 signals和slots机制是QT的根本。 slots和c++的成员函数(member function)几乎一样的,它们能定义为virtual,能overloaded,能定义为public,protected或private。能和c++其他成员函数一样 被直接调用,参量(paramters)能定义为任何类型,他与其它成员函数不同的是它能连接signal,当signal发射(emitted)时,它能自动调用。 它们格式一般为: connect(sender,SIGNAL(signal),receiver,SLOT(slot)); sender和receiver必需为指向一个QObject对象的指针。而signal和slot只需指出参量类型而不用写出产量名称。 以下是一些可能发生的例子。 a:一个signal能连接多个slots。 例如: connect(slider,SIGNAL(valueChange(int)),spinBox,SLOT(setValue(int))); connect(slider,SIGNAL(valueChange(int)),this,SLOT(updateValue(int))); b:多个signal能连接一个slots。 connect(lcd, SIGNAL(overflow()), this, SLOT(handleMathError())); connect(calculator, SIGNAL(divisionByZero()), this, SLOT(handleMathError())); c:一个signal能连接其他signal。 connect(lineEdit, SIGNAL(textChanged(const QString &)), this, SIGNAL(updateRecord(const QString &))); d:连接能够删除。 disconnect(lcd, SIGNAL(overflow()), this, SLOT(handleMathError())); 要成功连接signal到slot,必须要参量类型及数量相同。 connect(ftp, SIGNAL(rawCommandReply(int, const QString &)), this, SLOT(processReply(int, const QString &)));
但万事无绝对,如果signal比slot参量多,多出参量可以忽略。 例如:connect(ftp, SIGNAL(rawCommandReply(int, const QString &)), this, SLOT(checkErrorCode(int)));
|
|