QT 非模态对话框Dialog
- 单例模式,只要dialog不被销毁,弹出的永远都是同一个窗口
- Dialog 不会遮挡主窗口
- Dialog 添加放大缩小图标,且可以正常缩放到windows底部菜单栏
- 关闭主窗口,会关闭dialog
源码参考
头文件:
#ifndef DIALOGSELF_H
#define DIALOGSELF_H
#include <QDialog>
namespace Ui {
class DialogSelf;
}
class DialogSelf : public QDialog
{
Q_OBJECT
public:
explicit DialogSelf(QWidget *parent = nullptr);
~DialogSelf();
static DialogSelf *getInstance();
private:
Ui::DialogSelf *ui;
static DialogSelf *dialogSelf;
public slots:
void closeDialog();
};
#endif // DIALOGSELF_H
cpp文件:
#include "dialogself.h"
#include "ui_dialogself.h"
DialogSelf *DialogSelf::dialogSelf = nullptr;
DialogSelf::DialogSelf(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogSelf)
{
// Add maximize, minimize and close buttons, and display them normally
Qt::WindowFlags flags=Qt::Dialog;
flags |=Qt::WindowMinMaxButtonsHint;
flags |=Qt::WindowCloseButtonHint;
setWindowFlags(flags);
ui->setupUi(this);
}
DialogSelf::~DialogSelf()
{
dialogSelf = nullptr;
delete ui;
}
DialogSelf *DialogSelf::getInstance()
{
if(dialogSelf == nullptr)
{
dialogSelf = new DialogSelf();
}
return dialogSelf;
}
void DialogSelf::closeDialog()
{
if(dialogSelf != nullptr)
{
dialogSelf->close();
}
}
主窗口设置和调用代码:
// 在头文件中添加信号
signals:
void closeDialog();
// 在cpp中调用Dialog
void MainWindow::on_pushButton_clicked()
{
DialogSelf *dialogSelf = DialogSelf::getInstance();
dialogSelf->setAttribute(Qt::WA_DeleteOnClose, true);
connect(this, &MainWindow::closeDialog, dialogSelf, &DialogSelf::closeDialog);
dialogSelf->show();
// Raise () stands for the meaning put in the front; Lower () stands for the meaning behind
dialogSelf->raise();
dialogSelf->activateWindow();
}