剛開始看的時候看的雲裡霧裡的,現在稍微明白一點了。現在假設有一個form,一個MainWindow,如圖所示:
實現點擊PushButton,將文本框中的內容傳輸到MainWindow中,顯示為Label。界面我已經提前畫好。下面是備份代碼:
form.h:
#ifndef FORM_H #define FORM_H #include <QWidget> namespace Ui { class Form; } class Form : public QWidget { Q_OBJECT public: explicit Form(QWidget *parent = 0); ~Form(); signals: void sendData(QString); private slots: void on_sendBtn_clicked(); private: Ui::Form *ui; }; #endif // FORM_H
form.cpp:
#include "form.h" #include "ui_form.h" Form::Form(QWidget *parent) : QWidget(parent), ui(new Ui::Form) { ui->setupUi(this); } Form::~Form() { delete ui; } void Form::on_sendBtn_clicked() { emit sendData(ui->lineE->text()); }
MainWindow.h:
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "form.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void receiveData(QString data); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
MainWindow.cpp:
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); //傳值測試 Form *form=new Form; form->setGeometry(100,300,400,400); form->show(); connect(form,SIGNAL(sendData(QString)),this,SLOT(receiveData(QString))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::receiveData(QString data) { ui->label->setText(data); }
main.cpp:
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }