Qt中show()与exec()
1. show()默认显示的是非模态对话框,即此对话框出现后你还可以对其他窗口进行操作,可以用setModal函数进行设置窗口为模态,即无法操作其他窗口,即被阻塞. 而exec()出现的只能是模态对话框.
2. show()显示的窗口无论是否模态,都立刻将操作权返回, 运行下面代码;而exec()则是得等待exec出的窗口关闭后再运行下面代码.
qt帮助文档那个中写的是:Shows the dialog as a modal dialog, blocking until the user closes it. The function returns a DialogCode result., 返回的DialogCode 有QDialog::Accepted和QDialog::Rejected,可以根据返回值来进行判断等操作.
下面是一个小程序:
#ifndef DIALOG1_H #define DIALOG1_H #include <QDialog> #include "ui_dialog1.h" class dialog1 : public QDialog { Q_OBJECT public: dialog1(QWidget *parent = 0); protected slots: void buttonClicked(); private: Ui::dialog1 ui; }; #endif // DIALOG1_H
</pre><pre name="code" class="cpp">/*multiwindow.h*/
#ifndef MULTIWINDOW_H #define MULTIWINDOW_H #include "dialog1.h" #include <QtWidgets/QMainWindow> #include "ui_multiwindow.h" class multiWindow : public QMainWindow { Q_OBJECT public: multiWindow(QWidget *parent = 0); public slots: void button1Clicked(); private: Ui::multiWindowClass ui; dialog1 *dialog; }; #endif // MULTIWINDOW_H
/*dialog1.cpp*/
#include "dialog1.h" dialog1::dialog1(QWidget *parent) : QDialog(parent) { ui.setupUi(this); connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(buttonClicked())); } void dialog1::buttonClicked() { this->close(); }
/*multiwindow.cpp*/
#include "multiwindow.h" multiWindow::multiWindow(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(button1Clicked())); connect(ui.pushButton_3, SIGNAL(clicked()), this, SLOT(close())); dialog = new dialog1(this); } void multiWindow::button1Clicked() { this->hide(); //dialog->show(); dialog->exec(); this->show(); }
/*main.cpp*/
#include "multiwindow.h" #include <QtWidgets/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); multiWindow w; w.show(); return a.exec(); }
重点是multiwindow.cpp中的
<span style="white-space:pre"> </span>this->hide(); dialog->exec(); this->show();当按下按钮时,先将主窗口隐藏,然后显示exec的模态对话框,不继续执行下面代码,等待对话框的操作, 按下对话框的按钮后,对话框关闭,继续执行主对话框代码,将主对话框显示,即实现对话框的调用.
若将exec替换为show,则会出现两个对话框并存的现象.