QT之GUI学习笔记(五)---信号槽

原文地址 :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判断用于避免循环递归。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值