主要的精简代码就这些
#include <QDialog>// 创建模态框
QDialog dialog(this);
// 添加各种部件
// ...
// 因为创建在栈上面,所以需要阻止程序继续运行
dialog.exec();// 非模态框
QDialog dialog = new Dialog(this);
// 添加各种部件
// ...
dialog.show();
创建模态对话框
模态对话框通常通过调用 exec() 方法来显示,它会阻塞代码的执行,直到对话框关闭。
#include <QApplication>
#include <QDialog>
#include <QPushButton>int main(int argc, char *argv[]) {QApplication app(argc, argv);// 创建主窗口QWidget mainWindow;mainWindow.setWindowTitle("主窗口");mainWindow.resize(300, 200);// 创建一个按钮,点击后弹出模态对话框QPushButton modalButton("打开模态对话框", &mainWindow);modalButton.move(50, 50);// 创建模态对话框QDialog modalDialog(&mainWindow);modalDialog.setWindowTitle("模态对话框");// 设置模态对话框的属性modalDialog.setModal(true); // 确保对话框是模态的// 连接按钮的点击信号到槽函数,显示模态对话框QObject::connect(&modalButton, &QPushButton::clicked, [&]() {modalDialog.exec(); // 使用exec()显示模态对话框});mainWindow.show();return app.exec();
}
创建非模态对话框
非模态对话框通常通过调用 show() 方法来显示,它不会阻塞代码的执行,用户可以在对话框和父窗口之间自由切换。
#include <QApplication>
#include <QDialog>
#include <QPushButton>int main(int argc, char *argv[]) {QApplication app(argc, argv);// 创建主窗口QWidget mainWindow;mainWindow.setWindowTitle("主窗口");mainWindow.resize(300, 200);// 创建一个按钮,点击后弹出非模态对话框QPushButton modelessButton("打开非模态对话框", &mainWindow);modelessButton.move(50, 100);// 创建非模态对话框QDialog modelessDialog(&mainWindow);modelessDialog.setWindowTitle("非模态对话框");// 设置非模态对话框的属性modelessDialog.setModal(false); // 确保对话框是非模态的// 连接按钮的点击信号到槽函数,显示非模态对话框QObject::connect(&modelessButton, &QPushButton::clicked, [&]() {modelessDialog.show(); // 使用show()显示非模态对话框});mainWindow.show();return app.exec();
}
总结
模态对话框:使用 exec() 方法显示,会阻塞用户与父窗口的交互,直到对话框关闭。
非模态对话框:使用 show() 方法显示,不会阻塞用户与父窗口的交互,用户可以在对话框和父窗口之间自由切换。