《学习Qt之路2》笔记:Qt对话框模式

来源:互联网 发布:数据魔方登陆 编辑:程序博客网 时间:2024/05/03 17:37

Qt 中使用 QDialog 类实现对话框。就像主窗口一样,我们通常会设计一个类继承 QDialog。QDialog(及其子类,以及所有 Qt::Dialog 类型的类)的对于其 parent 指针都有额外的解释:如果 parent 为 NULL,则该对话框会作为一个顶层窗口,否则则作为其父组件的子对话框(此时,其默认出现的位置是 parent 的中心)。顶层窗口与非顶层窗口的区别在于,顶层窗口在任务栏会有自己的位置,而非顶层窗口则会共享其父组件的位置。

在MFC中对话框分为模态对话框和非模态对话框,Qt 支持模态对话框和非模态对话框。其中,Qt 有两种级别的模态对话框:应用程序级别的模态和窗口级别的模态,默认是应用程序级别的模态。应用程序级别的模态是指,当该种模态的对话框出现时,用户必须首先对对话框进行交互,直到关闭对话框,然后才能访问程序中其他的窗口。窗口级别的模态是指,该模态仅仅阻塞与对话框关联的窗口,但是依然允许用户与程序中其它窗口交互。

Qt 使用 QDialog::exec() 实现应用程序级别的模态对话框,使用 QDialog::open() 实现窗口级别的模态对话框,使用 QDialog::show() 实现非模态对话框。


部分代码:

#include "mainwindow.h"MainWindow::MainWindow(QWidget *parent): QMainWindow(parent){ui.setupUi(this);setWindowTitle(tr("Main Window"));openAction = new QAction(QIcon(":/images/"),tr("&Open"),this);openAction->setShortcut(QKeySequence::Open);openAction->setStatusTip(tr("Open an existing file"));connect(openAction,&QAction::triggered,this,&MainWindow::open);QMenu *file = menuBar()->addMenu(tr("&File"));file->addAction(openAction);QToolBar *toolBar = addToolBar(tr("&File"));toolBar->addAction(openAction);}MainWindow::~MainWindow(){}void MainWindow::open(){QDialog *dialog= new QDialog;//这里主要是怕内存泄露,当然也可以使用dialog->deleteLater();//setAttribute() 函数设置对话框关闭时,自动销毁对话框。deleteLater() 函数则会在当前事件循环结束时销毁该对话框。dialog->setAttribute(Qt::WA_DeleteOnClose);dialog->setWindowTitle(tr("Hello, dialog!"));dialog->show();}


原创粉丝点击