【1】.pro
1 QT += core gui 2 3 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 4 5 TARGET = TestDialog 6 TEMPLATE = app 7 8 # The following define makes your compiler emit warnings if you use 9 # any feature of Qt which as been marked as deprecated (the exact warnings 10 # depend on your compiler). Please consult the documentation of the 11 # deprecated API in order to know how to port your code away from it. 12 DEFINES += QT_DEPRECATED_WARNINGS 13 14 # You can also make your code fail to compile if you use deprecated APIs. 15 # In order to do so, uncomment the following line. 16 # You can also select to disable deprecated APIs only up to a certain version of Qt. 17 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 18 19 20 SOURCES += main.cpp 21 dialog.cpp 22 23 HEADERS += dialog.h 24 25 FORMS += dialog.ui
【2】.h
1 #ifndef DIALOG_H 2 #define DIALOG_H 3 4 #include <QDebug> 5 #include <QDialog> 6 #include <QPushButton> 7 #include <QHBoxLayout> 8 9 namespace Ui 10 { 11 class Dialog; 12 } 13 14 class MyDialog : public QDialog 15 { 16 public: 17 MyDialog(QWidget *parent = Q_NULLPTR); 18 ~MyDialog(); 19 20 private: 21 void init(); 22 23 private: 24 QPushButton* m_p1; 25 QPushButton* m_p2; 26 27 }; 28 29 class Dialog : public QDialog 30 { 31 Q_OBJECT 32 33 public: 34 explicit Dialog(QWidget *parent = 0); 35 ~Dialog(); 36 37 private slots: 38 void onPushButton(); 39 40 private: 41 Ui::Dialog *ui; 42 MyDialog *m_pDialog; 43 }; 44 45 #endif // DIALOG_H
【3】.cpp
1 #include "dialog.h" 2 #include "ui_dialog.h" 3 4 MyDialog::MyDialog(QWidget *parent) : QDialog(parent) 5 { 6 init(); 7 } 8 9 MyDialog::~MyDialog() 10 { 11 12 } 13 14 void MyDialog::init() 15 { 16 m_p1 = new QPushButton(this); 17 m_p1->setText(QString("OK")); 18 m_p2 = new QPushButton(this); 19 m_p2->setText(QString("Cancel")); 20 connect(m_p1, &QPushButton::clicked, this, &MyDialog::accept); 21 connect(m_p2, &QPushButton::clicked, this, &MyDialog::reject); 22 QHBoxLayout* pHLayout = new QHBoxLayout(this); 23 pHLayout->addWidget(m_p1); 24 pHLayout->addWidget(m_p2); 25 setLayout(pHLayout); 26 } 27 28 Dialog::Dialog(QWidget *parent) : 29 QDialog(parent), 30 ui(new Ui::Dialog) 31 { 32 ui->setupUi(this); 33 m_pDialog = new MyDialog(); 34 connect(ui->pushButton, &QPushButton::clicked, this, &Dialog::onPushButton); 35 } 36 37 Dialog::~Dialog() 38 { 39 delete ui; 40 if (m_pDialog != Q_NULLPTR) 41 { 42 delete m_pDialog; 43 m_pDialog = Q_NULLPTR; 44 } 45 } 46 47 void Dialog::onPushButton() 48 { 49 int nRet = m_pDialog->exec(); 50 if (nRet == QDialog::Accepted) 51 { 52 qDebug() << "Click OK Button"; 53 qApp->exit(0); 54 } 55 else if (nRet == QDialog::Rejected) 56 { 57 qDebug() << "Click Cancel Button"; 58 return; 59 } 60 }
【4】main
1 #include "dialog.h" 2 #include <QApplication> 3 4 int main(int argc, char *argv[]) 5 { 6 QApplication a(argc, argv); 7 Dialog w; 8 w.show(); 9 10 return a.exec(); 11 }
【5】验证一个问题
Good Good Study, Day Day Up.
顺序 选择 循环 总结