在實際開發中,我們會有這樣一種需求,一個提示框,使用者可以手動關閉,或者在使用者沒有操作的情況下,顯示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();