qt 窗体间通信
利用qt的信号和槽,可以完成窗体间的通信,下面列出父子窗口利用信号和槽的相关代码。
parent窗口:
//parent.h #ifndef PARENT_H #define PARENT_H #include <QMainWindow> #include "child.h" namespace Ui { class Parent; } class Parent : public QMainWindow { Q_OBJECT public: explicit Parent(QWidget *parent = 0); ~Parent(); signals: //打开子窗口的信号 void childOpen(const QString &message); private slots: //打开子窗口 void on_pushButtonParent_clicked(); //接收子窗口关闭的信号的槽 void on_child_closed(const QString &message); private: Ui::Parent *ui; }; #endif // PARENT_H
//parent.cpp #include "parent.h" #include "ui_parent.h" Parent::Parent(QWidget *parent) : QMainWindow(parent), ui(new Ui::Parent) { ui->setupUi(this); } Parent::~Parent() { delete ui; } void Parent::on_pushButtonParent_clicked() { Child *child = new Child(); //向子窗口发送信号 connect(this, SIGNAL(childOpen(QString)), child, SLOT(on_open(QString))); emit childOpen("子窗口打开,父窗口传递消息到子窗口"); //连接子窗口关闭的信号 connect(child, SIGNAL(closed(QString)), this, SLOT(on_child_closed(QString))); child->exec(); //注意,需要关闭,否则到时打开几次子窗口就会触发几次窗口打开信号 disconnect(this, SIGNAL(childOpen(QString)), child, SLOT(on_open(QString))); } void Parent::on_child_closed(const QString &message) { QMessageBox::information(NULL, "父窗口", message); }
child窗体:
//child.h #ifndef CHILD_H #define CHILD_H #include <QDialog> #include <QMessageBox> namespace Ui { class Child; } class Child : public QDialog { Q_OBJECT public: explicit Child(QWidget *parent = 0); ~Child(); public slots: //接收窗口打开信号的槽 void on_open(const QString &message); //关闭窗口 void on_pushButtonChild_clicked(); signals: //窗口关闭的信号 void closed(const QString &message); private: Ui::Child *ui; }; #endif // CHILD_H
//child.cpp #include "child.h" #include "ui_child.h" Child::Child(QWidget *parent) : QDialog(parent), ui(new Ui::Child) { ui->setupUi(this); } Child::~Child() { delete ui; } void Child::on_open(const QString &message) { QMessageBox::information(NULL, "子窗口", message); } void Child::on_pushButtonChild_clicked() { this->close(); emit closed("子窗口关闭,向父窗口发送消息"); }
结果截图: