QT 非模态对话框Dialog

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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值