[英]Qt C++: how to add a simple countdown timer?
我是Qt C ++的新手,從網上找到的一些資源中,我無法僅提取我需要在表單中添加倒數計時器的位。 我沒有嘗試添加任何按鈕或其他功能。 只需要有一個從1:00開始然后遞減直到達到0:00的計時器,這時我需要顯示某種消息來指示用戶時間到了。 我認為也許添加一個標簽來顯示計時器將是一種簡單的方法(但是現在確定我是否正確)。
到目前為止,我創建了一個新的Qt Application項目,在我的主窗體中添加了標簽,並從http://doc.qt.io/archives/qt-4.8/timers.html獲得了一些計時器代碼到mainwindow.cpp中。 :
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//Initialize "countdown" label text
ui->countdown->setText("1:00");
//Connect timer to slot so it gets updated
timer = new QTimer();
connect(timer, SIGNAL(timeout()), this, SLOT(updateCountdown()));
//It is started with a value of 1000 milliseconds, indicating that it will time out every second.
timer->start(1000);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::updateCountdown()
{
//do something along the lines of ui->countdown->setText(....);
}
在mainwindow.h中,我添加了QTimer *timer;
;。 作為公共屬性,並且還會void updateCountdown();
作為專用插槽。
但是我不確定如何從這里繼續。 我認為下一步是每秒減少計時器,並在“倒數”標簽上顯示出來(這將在updateCountdown插槽上完成),但我不知道如何進行。 我也不確定倒數到0:00時如何觸發消息(可能在QFrame上)。
從QTimer文檔中 ,您的配置中每隔1秒鍾調用一次updateCountdown()
函數。 因此,每次調用此函數並在UI中進行更新時,您都應將計時器減少一秒鍾。 當前您不在任何地方存儲時間,因此建議您現在將其添加為全局QTime time(0, 1, 0)
,例如QTime time(0, 1, 0)
QTime Documentation 。
然后在updateCountdown()
內部,調用time.addSecs(-1);
然后ui->countdown->setText(time.toString("m:ss"));
。 然后很容易檢查是否為“ 0:00”並執行其他操作。
我希望這有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.