一、信號與槽
用於在兩個不同控件間進行數據傳輸。
子控件
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);
