Qt实现简单倒计时

1.效果图

效果gif

2.代码结构 

3.关键类

 QWaittingDialog.h

#ifndef QWAITTINGDIALOG_H
#define QWAITTINGDIALOG_H

#include <QDialog>
#include <QLabel>
#include <QThread>
#include <QTimer>

class QWaittingDialog : public QDialog
{
    Q_OBJECT
public:
    explicit QWaittingDialog(QWidget *parent = nullptr);

    void Run(int nStartValue);

signals:

public slots:
    void on_timer_timeout();

private:
    QLabel*             m_pLabel;
    QTimer*             m_pTimer;
    int                 m_nStartValue;


    // QWidget interface
protected:
    void paintEvent(QPaintEvent* event);
};


#endif // QWAITTINGDIALOG_H

QWaittingDialog.cpp

#include "QWaittingDialog.h"
#include <QPainter>
#include <QVBoxLayout>

QWaittingDialog::QWaittingDialog(QWidget *parent) : QDialog(parent)
    , m_nStartValue(0)
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::Tool | Qt::WindowStaysOnTopHint);

    // 全透明
    setAttribute(Qt::WA_TranslucentBackground);

    QVBoxLayout* pVBoxLayout = new QVBoxLayout(this);

    m_pLabel = new QLabel();
    pVBoxLayout->addWidget(m_pLabel);

    m_pLabel->setText("");
    m_pLabel->setAlignment(Qt::AlignCenter);

    QString strStyle = "QLabel{"
                       "font-family: \"Microsoft YaHei\";"
                       "font-size: 128px;"
                       "color: rgb(50, 50, 50, 180);"
                       "}";

    m_pLabel->setStyleSheet(strStyle);

    m_pTimer = new QTimer(this);
    connect(m_pTimer, &QTimer::timeout, this, &QWaittingDialog::on_timer_timeout);
    m_pTimer->setInterval(1000);
}

void QWaittingDialog::Run(int nStartValue)
{
    m_pTimer->stop();

    m_nStartValue = nStartValue;

    QWidget* parent = parentWidget();
    move(parent->pos());
    resize(parent->rect().width(), parent->rect().height());

    on_timer_timeout();
    m_pTimer->start();

    show();
}

void QWaittingDialog::on_timer_timeout()
{
    if (m_nStartValue == 0)
    {
        m_pTimer->stop();
        close();
        return;
    }

    m_pLabel->setText(QString::number(m_nStartValue));

    m_nStartValue--;
}



void QWaittingDialog::paintEvent(QPaintEvent* event)
{
    // 避免鼠标穿透
    QPainter painter(this);
    painter.fillRect(this->rect(), QColor(240, 240, 240, 1));   // 配合全透明属性一起使用
}

调用示例

    QWaittingDialog* dlg = new QWaittingDialog(this);
    dlg->Run(3);

资源下载链接:下载

(该资源正在审核,待审核通过后更新)

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值