刚开始看的时候看的云里雾里的,现在稍微明白一点了。现在假设有一个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(); }