Qt入门之connect, SIGNAL, SLOT

来源:互联网 发布:知乎 盐水去甲醛 编辑:程序博客网 时间:2024/04/29 07:28

http://blog.csdn.net/xgbing/article/details/7764326

在QT中,事件处理信号叫做SIGNAL,事件处理函数叫做SLOT,两者关联函数是QOjbect::connect。

示例:

[cpp] view plaincopy
  1. connect(sender, SIGNAL(signal), receiver, SLOT(slot));  


sender: 指触发的控件。

signel:sender中定义的信号。

receiver:可以是一个类。

slot: 在类中定义的处理函数。

 

在类中定义slot的方法如下:

[cpp] view plaincopy
  1. class PushBtn : public QPushButton  
  2. {  
  3.     Q_OBJECT  
  4.   
  5. public:  
  6.     ...  
  7.   
  8. private slots:        //将事件处理函数放在此关键字下  
  9.     void slot_fun();  
  10.         ...  
  11.   
  12. };  


 注意此类的定义须在头文件中,否则编译时会报错:

error LNK2001: 无法解析的外部符号 ...

 

另外,QT库的类内部定义的许多solt,我们可以直接使用。

如按下一个按键时退出:

[cpp] view plaincopy
  1.  1 #include <QApplication>  
  2.  2 #include <QPushButton>  
  3.  3 int main(int argc, char *argv[])  
  4.  4 {  
  5.  5     QApplication app(argc, argv);  
  6.  6     QPushButton *button = new QPushButton("Quit");  
  7.  7     QObject::connect(button, SIGNAL(clicked()),  
  8.  8                      &app, SLOT(quit()));  
  9.  9     button->show();  
  10. 10     return app.exec();  
  11. 11 } 

0 0