通过实现两个对话框互相发送消息的功能来熟悉Qt的信号和槽。具体功能:程序为单对话框程序,点击其上的打开按钮可以再次打开一个对话框,两个对话框都有发送消息按钮、输入消息文本框和编辑消息文本框,并实现互发消息功能。
主对话框头文件:
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); private: Ui::Dialog *ui; private slots: void openDialog(); void receiveMessage(QString message); void pushButtonSendMessage_click(); signals: void sendMessage(QString); }; #endif // DIALOG_H
主对话框实现文件:
#include "dialog.h" #include "ui_dialog.h" #include "dialogother.h" namespace { DialogOther* other; } Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); other=new DialogOther(); connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(openDialog())); connect(ui->pushButtonSendMessage,SIGNAL(clicked(bool)),this,SLOT(pushButtonSendMessage_click())); connect(this,SIGNAL(sendMessage(QString)),other,SLOT(receiveMessage(QString))); connect(other,SIGNAL(sendMessage(QString)),this,SLOT(receiveMessage(QString))); } Dialog::~Dialog() { delete ui; delete other; } void Dialog::openDialog() { other->show(); } void Dialog::receiveMessage(QString message) { ui->textEdit->setText(nullptr); ui->textEdit->setText(message); } void Dialog::pushButtonSendMessage_click() { emit sendMessage(ui->lineEdit->text()); }
另一个对话框头文件:
#ifndef DIALOGOTHER_H #define DIALOGOTHER_H #include <QDialog> namespace Ui { class DialogOther; } class DialogOther : public QDialog { Q_OBJECT public: explicit DialogOther(QWidget *parent = 0); ~DialogOther(); private: Ui::DialogOther *ui; public slots: void receiveMessage(QString message); void pushButtonSendMessage_Click(); signals: void sendMessage(QString); }; #endif // DIALOGOTHER_H
另一个对话框实现文件:
#include "dialogother.h" #include "ui_dialogother.h" DialogOther::DialogOther(QWidget *parent) : QDialog(parent), ui(new Ui::DialogOther) { ui->setupUi(this); connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(pushButtonSendMessage_Click())); } DialogOther::~DialogOther() { delete ui; } void DialogOther::receiveMessage(QString message) { ui->textEdit->setText(nullptr); ui->textEdit->setText(message); } void DialogOther::pushButtonSendMessage_Click() { emit sendMessage(ui->lineEdit->text()); }