QT QDialog 对话框显示几秒钟自动关闭

在实际开发中,我们会有这样一种需求,一个提示框,用户可以手动关闭,或者在用户没有操作的情况下,显示3秒钟然后自动关闭,这样应该怎样做呢?

我们的思路应该是这样的:

1.对话框构造函数里,设置一个定时器

2.定时器槽函数设置为close()

看代码

.h

#ifndef SUBMITSCOREERRORDLG_H
#define SUBMITSCOREERRORDLG_H

#include <QDialog>
#include <QTimer>

enum TipsType
{
    TipsType_Unknown =          0,
    TipsType_Warnning =         1,//警告
    TipsType_Ok =               2//成功
};

namespace Ui {
class TipsDlg;
}

class TipsDlg : public QDialog
{
    Q_OBJECT

public:
    explicit TipsDlg(TipsType type, const QString &msg, QWidget *parent = 0);
    ~TipsDlg();

    void startTimer();

private:
    /**
     * @brief initFrame 初始化对话框
     * @param msg       提示信息
     */
    void initFrame(const QString &msg);

private:
    Ui::TipsDlg *ui;
    TipsType m_type;
    QTimer *m_pTimer;
};

.cpp


#include "tipsdlg.h"
#include "ui_tipsdlg.h"

TipsDlg::TipsDlg(TipsType type, const QString &msg, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TipsDlg),
    m_type(type)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint | Qt::Tool | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground);

    initFrame(msg);

    m_pTimer = new QTimer(this);
    m_pTimer->setSingleShot(true);
    connect(m_pTimer, &QTimer::timeout, this, [=](){this->close();});
}

TipsDlg::~TipsDlg()
{
    if(m_pTimer != Q_NULLPTR)
        m_pTimer->deleteLater();

    delete ui;
}

void TipsDlg::startTimer()
{
    m_pTimer->start(3000);
}

void TipsDlg::initFrame(const QString &msg)
{
    if(TipsType_Warnning == m_type)//警告
    {
        ui->iconLabel->setStyleSheet("QLabel{background-image: url(:/qc/warnning);background-repeat:no-repeat;}");
    }
    else if(TipsType_Ok == m_type)//成功
    {
        ui->iconLabel->setStyleSheet("QLabel{background-image: url(:/qc/tips_ok);background-repeat:no-repeat;}");
    }

    ui->tipsLabel->setText(msg);

}

怎么调用呢?

    TipsDlg dlg(TipsType_Ok, "提交评分成功", this->topLevelWidget());
    dlg.setAttribute(Qt::WA_ShowModal, true);
    dlg.startTimer();
    dlg.exec();

猜你喜欢

转载自blog.csdn.net/xiezhongyuan07/article/details/79885546