萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Qt 實作倒數計時器:考研倒數範例完整解析

專案建立

  1. Qt Creator → New Project → Application → Qt Widgets Application
  2. 專案名稱:CountdownTimer
  3. 套件選擇:Core, Gui, Widgets

main.cpp 完整程式碼

#include 
#include 
#include 
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QLabel *label = new QLabel;
    label->setWindowTitle("考研倒數計時");
    label->setAlignment(Qt::AlignCenter);

    // 目標日期:2025-12-20 (可改為命令列參數或設定檔)
    QDate targetDate(2025, 12, 20);
    QDate currentDate = QDate::currentDate();

    qint64 daysLeft = currentDate.daysTo(targetDate);
    if (daysLeft < 0) daysLeft = 0; // 已過期

    QString text = QString("距離考研還有 %1 天").arg(daysLeft);
    label->setText(text);

    QFont font("Microsoft JhengHei", 36, QFont::Bold);
    label->setFont(font);
    label->resize(400, 100);
    label->show();

    return a.exec();
}

進階:即時更新的動態倒數計時器

#include 
#include 
#include 
#include 
#include 

class CountdownWidget : public QLabel
{
    Q_OBJECT
public:
    CountdownWidget(QDateTime target, QWidget* parent = nullptr)
        : QLabel(parent), m_target(target)
    {
        setAlignment(Qt::AlignCenter);
        setFont(QFont("Microsoft JhengHei", 36, QFont::Bold));
        resize(500, 150);

        m_timer = new QTimer(this);
        connect(m_timer, &QTimer::timeout, this, &CountdownWidget::updateDisplay);
        m_timer->start(1000); // 每秒更新
        updateDisplay();
    }

private slots:
    void updateDisplay()
    {
        QDateTime now = QDateTime::currentDateTime();
        qint64 secs = now.secsTo(m_target);
        if (secs <= 0)
        {
            setText("考試開始!加油!");
            setStyleSheet("color: red;");
            m_timer->stop();
            return;
        }

        int days = secs / 86400;
        int hours = (secs % 86400) / 3600;
        int mins = (secs % 3600) / 60;
        int sec = secs % 60;

        setText(QString("距離考研:%1天 %2:%3:%4")
                    .arg(days)
                    .arg(hours, 2, 10, QChar('0'))
                    .arg(mins, 2, 10, QChar('0'))
                    .arg(sec, 2, 10, QChar('0')));
    }

private:
    QDateTime m_target;
    QTimer* m_timer;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    CountdownWidget w(QDateTime(QDate(2025,12,20), QTime(9,0,0)));
    w.show();
    return a.exec();
}

關鍵 Qt 類別說明

類別用途
QDate日期運算,daysTo() 計算天數差
QDateTime日期時間精確到秒,secsTo() 計算秒差
QTimer週期性觸發 timeout() 訊號
QLabel輕量級文字/圖片顯示,支援富文本與樣式表
QFont字體、大小、粗細設定

部署為獨立執行檔

  1. 建置模式切換為 Release
  2. 執行 windeployqt CountdownTimer.exe (Qt 安裝目錄/bin) 自動複製所需 DLL
  3. 打包整個資料夾分發

擴充功能建議

  • 系統托盤常駐,右鍵選單顯示剩餘時間
  • 支援多目標事件 (考試、生日、專案截止)
  • 資料持久化 (QSettings) 記住使用者設定的目標日期
  • 跨平台編譯:macOS (App Bundle)、Linux (AppImage/Flatpak)、WebAssembly (Qt for WebAssembly)
copyright © 萬盛學電腦網 all rights reserved