现在的位置: 首页 > 综合 > 正文

[QT]信号与槽机制

2012年10月30日 ⁄ 综合 ⁄ 共 1300字 ⁄ 字号 评论关闭

信号(signal)和槽(slot)

  • 类似于windows中的消息和消息响应
  • 都是通过C++类成员函数实现的
  • 信号和槽是通过连接实现相互关联的
  • 包含信号或槽的类必须从QObject继承

信号(signal)和槽(slot)——声明

class Employee : public QObject
{
	Q_OBJECT
	public:
		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)));

抱歉!评论已关闭.