1. 对话框简介
对话框简介:通常是一个顶层窗口,出现在程序最上层,用于实现短期任务或者简洁的用户交互。
对话框分为模态对话框和非模态对话框:
- 模态对话框,会阻塞同一应用程序中其他窗口的输入。
- 非模态对话框,可以在显示的同时,也能对其他窗口进行操作。
2. 模态对话框、非模态对话框 区别
示例:
1)新建工程:使用QMainWindow类。
2)源码:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMenu>
#include <QMenuBar>
#include <QAction>
#include <QDialog>
#include <QDebug>
#include <QMessageBox>
#include <QFileDialog>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
QDialog dlg;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
resize(480, 320);
setWindowTitle("Hello");
// 新建菜单栏
QMenuBar *mBar = menuBar();
setMenuBar(mBar);
// 添加菜单
QMenu *menu = mBar->addMenu("对话框");
// 添加菜单项,添加信号槽弹出 模态对话框
QAction *p1 = menu->addAction("模态对话框");
connect( p1, &QAction::triggered,
[=]()
{
dlg.setWindowTitle("模态对话框");
dlg.exec();
qDebug() << "111";
});
// 添加菜单项,添加信号槽弹出 非模态对话框
QAction *p2 = menu->addAction("非模态对话框");
connect( p2, &QAction::triggered,
[=]()
{
// 可以用全作用域的写法,也可用堆区创建,加上生命范围
//dlg.show();
//qDebug() << "111";
QDialog *p = new QDialog;
p->setAttribute(Qt::WA_DeleteOnClose);// 应用控件时自动释放
p->setWindowTitle("非模态对话框");
p->show();
qDebug() << "111";
});
}
MainWindow::~MainWindow()
{
}
setAttribute(Qt::WA_DeleteOnClose);// 对话框关闭时,堆区自动释放。
3)现象:
- 打开模态对话框时,不会输出111,关闭对话框时候才会输出111.
- 打开非模态对话框时,会直接输出111.