考研倒數、專案截止日提醒、活動開跑計時等固定目標日期的倒數顯示。
main.cpp)#include <QApplication>
#include <QLabel>
#include <QDate>
#include <QFont>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QLabel *label = new QLabel;
QDate today = QDate::currentDate();
QDate target(2025, 12, 25); // 目標日期
qint64 days = today.daysTo(target); // 可為負值(已過期)
QString text = QString("距離目標還有 %1 天").arg(days);
label->setText(text);
label->setWindowTitle("倒數計時器");
label->setAlignment(Qt::AlignCenter);
QFont font; font.setPointSize(28); label->setFont(font);
label->resize(360, 80);
label->show();
return app.exec();
}
CountdownWidget// countdownwidget.h
#ifndef COUNTDOWNWIDGET_H
#define COUNTDOWNWIDGET_H
#include <QWidget>
#include <QDateTime>
#include <QTimer>
class QLabel;
class CountdownWidget : public QWidget {
Q_OBJECT
public:
explicit CountdownWidget(QDateTime target, QWidget* parent = nullptr);
private slots:
void updateDisplay();
private:
QLabel* m_label;
QTimer* m_timer;
QDateTime m_target;
};
#endif
// countdownwidget.cpp
#include "countdownwidget.h"
#include <QLabel>
#include <QVBoxLayout>
#include <QFont>
CountdownWidget::CountdownWidget(QDateTime target, QWidget* parent)
: QWidget(parent), m_target(target) {
setWindowTitle("倒數計時");
resize(400, 120);
m_label = new QLabel(this);
m_label->setAlignment(Qt::AlignCenter);
QFont f; f.setPointSize(32); m_label->setFont(f);
QVBoxLayout* lay = new QVBoxLayout(this);
lay->addWidget(m_label);
setLayout(lay);
m_timer = new QTimer(this);
connect(m_timer, &QTimer::timeout, this, &CountdownWidget::updateDisplay);
m_timer->start(1000); // 每秒更新
updateDisplay(); // 立即顯示一次
}
void CountdownWidget::updateDisplay() {
qint64 secs = QDateTime::currentDateTime().secsTo(m_target);
if (secs < 0) {
m_label->setText("時間已到!");
m_timer->stop();
return;
}
int d = secs / 86400;
int h = (secs % 86400) / 3600;
int m = (secs % 3600) / 60;
int s = secs % 60;
m_label->setText(QString("%1天 %2:%3:%4").arg(d).arg(h,2,10,QChar('0')).arg(m,2,10,QChar('0')).arg(s,2,10,QChar('0')));
}
main.cpp 中使用元件#include <QApplication>
#include <QDateTime>
#include "countdownwidget.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDateTime target(QDate(2025,12,25), QTime(0,0,0));
CountdownWidget w(target);
w.show();
return app.exec();
}
.pro 關鍵設定QT += core gui widgets
CONFIG += c++17
TARGET = CountdownDemo
TEMPLATE = app
SOURCES += main.cpp countdownwidget.cpp
HEADERS += countdownwidget.h
| 問題 | 解決方案 |
|---|---|
| 視窗關閉後程式未退出 | 確保 QApplication::quitOnLastWindowClosed() 預設為 true,或在主視窗關閉事件呼叫 qApp->quit() |
| 跨時區部署 | 使用 QDateTime::currentDateTimeUtc() 並將目標時間統一轉 UTC |
| 高 DPI 顯示模糊 | 在 main() 最前加 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); |
| 需支援毫秒/週數顯示 | 擴充 updateDisplay() 格式化邏輯,或加入 setDisplayFormat() 讓使用者自訂 |
從 20 行極簡版本到可複用的 CountdownWidget,Qt 的訊號/槽機制與 QTimer 讓週期性 UI 更新變得直觀。實務專案可進一步加入設定對話框、系統托盤圖示、聲音提醒等功能,打造完整的桌面倒數工具。