QT--彈出新的對話框 show()/exec()的區別


 

  show()顯示非模態對話框,exec()顯示模態對話框。

非模態對話框不會阻塞程序的線程,因此

  如果你的對話框時創建在棧上,跳出作用域之后,對象便銷毀了,對話框會一閃而過;

  如果使用new在堆上創建對話框,跳出作用域之后對象不能被銷毀,但是建立在堆上需要考慮釋放內存的問題;

非模態對話框不會阻塞線程,可能用戶還沒來得及輸入數據,就已經執行之后的代碼。

 

模態對話框開啟一個事件循環,會阻塞程序的線程,函數返回之后,直接獲取對話框的數據。

新建一個項目,主界面如下:

非模態窗口打開代碼如下:

 1 #ifndef NEWMODALDIALOG_H
 2 #define NEWMODALDIALOG_H
 3 
 4 #include <QDialog>
 5 
 6 namespace Ui {
 7 class newModalDialog;
 8 }
 9 
10 class newModalDialog : public QDialog
11 {
12     Q_OBJECT
13 
14 public:
15     explicit newModalDialog(QWidget *parent = 0);
16     ~newModalDialog();
17 
18 signals:
19     void receiveData(QString s);
20 private:
21     Ui::newModalDialog *ui;
22     void accept();
23 };
24 
25 #endif // NEWMODALDIALOG_H
非模態窗口h文件

 

 1 #include "newmodaldialog.h"
 2 #include "ui_newmodaldialog.h"
 3 
 4 newModalDialog::newModalDialog(QWidget *parent) :
 5     QDialog(parent),
 6     ui(new Ui::newModalDialog)
 7 {
 8     ui->setupUi(this);
 9 }
10 
11 newModalDialog::~newModalDialog()
12 {
13     delete ui;
14 }
15 
16 void newModalDialog::accept()
17 {
18     QString data = ui->lineEdit_showText->text();
19     emit receiveData(data); //emit發送信號
20     QDialog::accept();
21 }
非模態窗口cpp文件

 

 1 void MainWindow::on_pushButton_modelessDlg_clicked()
 2 {
 3     newModalDialog *newDlg = new newModalDialog();
 4     connect(newDlg,&newModalDialog::receiveData,this,&MainWindow::displayData);
 5     newDlg->show();
 6 
 7 }
 8 
 9 void MainWindow::displayData(const QString& data)
10 {
11     ui->label_getInput->setText(data);
12 }
主界面主要代碼

 

 

模態窗口打開主要代碼如下:

 1 #ifndef NEWDIALOG_H
 2 #define NEWDIALOG_H
 3 
 4 ///模態對話框
 5 
 6 #include <QDialog>
 7 
 8 namespace Ui {
 9 class newDialog;
10 }
11 
12 class newDialog : public QDialog
13 {
14     Q_OBJECT
15 
16 public:
17     explicit newDialog(QWidget *parent = 0);
18     ~newDialog();
19 
20      QString getinput(); //獲取輸入的數據
21 private:
22     Ui::newDialog *ui;
23 };
24 
25 #endif // NEWDIALOG_H
模態對話框窗口h文件

 

 1 #include "newdialog.h"
 2 #include "ui_newdialog.h"
 3 
 4 newDialog::newDialog(QWidget *parent) :
 5     QDialog(parent),
 6     ui(new Ui::newDialog)
 7 {
 8     ui->setupUi(this);
 9 }
10 
11 newDialog::~newDialog()
12 {
13     delete ui;
14 }
15 
16 QString newDialog::getinput()
17 {
18     return ui->lineEdit_input->text();
19 }
模態對話框窗口cpp文件

 

1 void MainWindow::on_pushButton_showNewDialog_clicked()
2 {
3     newDialog newDlg;
4     newDlg.exec();
5     ui->label_getInput->setText(newDlg.getinput());
6 }
主界面主要代碼

 

 

參考:https://blog.csdn.net/knightaoko/article/details/53825314

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM