QT事件(信号与槽)用法

一、信号与槽

  用于在两个不同控件间进行数据传输。

子控件

  PageButton.h

 1 #ifndef PAGEBUTTON_H
 2 #define PAGEBUTTON_H
 3 
 4 #include "common.h"
 5 
 6 class PageButton : public QPushButton
 7 {
 8     Q_OBJECT
 9 public:
10     PageButton();
11     PageButton(QString text);
12 
13 signals:
14     void sendData(QJsonObject);
15 
16 private slots:
17     void myClickEvent();
18 
19 public:
20     QJsonObject data;
21 };
22 
23 #endif // PAGEBUTTON_H

  PageButton.cpp

 1 #include "pagebutton.h"
 2 
 3 PageButton::PageButton()
 4 {
 5     this->setText("..");
 6     connect(this, &PageButton::clicked, this, &PageButton::myClickEvent);
 7 }
 8 
 9 PageButton::PageButton(QString text)
10 {
11     this->setText(text);
12     connect(this, &PageButton::clicked, this, &PageButton::myClickEvent);
13 }
14 
15 void PageButton::myClickEvent()
16 {
17     qDebug() << "click";
18     emit sendData(data);//发送数据
19 }

 

父组件

  声明Slots

1 private slots:
2     void on_btnView_clicked();
3     void myEvent(QJsonObject obj);

  定义Slots

1 void MainWindow::myEvent(QJsonObject obj)
2 {
3     qDebug() << obj.take("caption").toString();
4 }

  绑定事件,注册事件

1         QString text = QString("P: %1").arg((i+1));
2         PageButton * btn = new PageButton(text);
3         btn->data = page;
4         connect(btn, &PageButton::sendData, this, &MainWindow::myEvent);

 

posted @ 2020-10-13 16:46  无脑仔的小明  阅读(671)  评论(0编辑  收藏  举报