QT信号槽传递参数技巧

来源:互联网 发布:大数据支撑平台 编辑:程序博客网 时间:2024/06/05 12:43

转载地址:http://blog.csdn.net/you_shou/article/details/50970002


信号槽如何传递参数(或带参数的信号槽)

利用Qt进行程序开发时,有时需要信号槽来完成参数传递。带参数的信号槽在使用时,有几点需要注意的地方,下面结合实例进行介绍。

第一点:当信号与槽函数的参数数量相同时,它们参数类型要完全一致。

信号:

[cpp] view plain
  1. void iSignal(int b);  

槽:

[cpp] view plain
  1. void MainWindow::iSlot(int b)  
  2. {  
  3.     QString qString;  
  4.     qDebug()<<qString.number(b);  
  5. }  

信号槽绑定:

[cpp] view plain
  1. connect(this, SIGNAL(iSignal(int)), this, SLOT(iSlot(int)));  

发送信号:

[cpp] view plain
  1. emit iSignal(5);  


结果:

可以看出,参数已经成功传递。


第二点:当信号的参数与槽函数的参数数量不同时,只能是信号的参数数量多于槽函数的参数数量,且前面相同数量的参数类型应一致,信号中多余的参数会被忽略。

信号:

[html] view plain
  1. void iSignal(int a, float b);  

槽:

[html] view plain
  1. void MainWindow::iSlot(int b)  
  2. {  
  3.     QString qString;  
  4.     qDebug()<<qString.number(b);  
  5. }  

信号槽:

[html] view plain
  1. connect(this, SIGNAL(iSignal(int, float)), this, SLOT(iSlot(int)));  

发送信号:

[html] view plain
  1. emit iSignal(5, 0.3);  

结果:



此外,在不进行参数传递时,信号槽绑定时也是要求信号的参数数量大于等于槽函数的参数数量。这种情况一般是一个带参数的信号去绑定一个无参数的槽函数。如下例所示。

信号:

[cpp] view plain
  1. void iSignal(int a, float b);  
槽函数:

[cpp] view plain
  1. void MainWindow::iSlot() //int b  
  2. {  
  3.     QString qString = "I am lyc_daniel.";  
  4.     qDebug()<<qString;  
  5. }  

信号槽:

[html] view plain
  1. connect(this, SIGNAL(iSignal(int, float)), this, SLOT(iSlot()));  

发送信号:

[html] view plain
  1. emit iSignal(5, 0.3);  

结果: