目录
main.cpp
指针调用:
类调用踩坑实录
"countdownTimer.h"
"countdownTimer.cpp"
main.cpp
#include <QApplication>
#include <QLabel>
#include "CountdownTimer.h"int main(int argc, char *argv[])
{QApplication app(argc, argv);QLabel label;label.show();auto updateLabel = [&label](const QString &text) {label.setText(text);};int totalTime = 60000; // 设置倒计时为60秒CountdownTimer countdownTimer(updateLabel, totalTime);countdownTimer.start();return app.exec();
}
指针调用:
#include <QApplication>
#include <QLabel>
#include "CountdownTimer.h"int main(int argc, char *argv[])
{QApplication app(argc, argv);QLabel* label = new QLabel; // label 是一个指针label->show();auto updateLabel = [label](const QString &text) { // 使用捕获列表捕获label指针label->setText(text); // 使用箭头操作符访问setText方法};int totalTime = 60000; // 设置倒计时为60秒CountdownTimer countdownTimer(updateLabel, totalTime);countdownTimer.start();int result = app.exec();delete label; // 清理动态分配的内存return result;
}
类调用踩坑实录
如果在类里面调用,CountdownTimer不能是函数内变量,要写成类变量,否则函数结束,就被销毁了。计时器无效了。
auto callback = std::bind(&Countwidget::updateLabel, this, std::placeholders::_1);int totalTime = 5000; // 设置倒计时为60秒countdownTimer=new CountdownTimer(callback, totalTime);countdownTimer->start();
"countdownTimer.h"
#ifndef COUNTDOWNTIMER_H
#define COUNTDOWNTIMER_H#include <QObject>
#include <QTimer>
#include <functional>
#include <QString>class CountdownTimer : public QObject
{Q_OBJECTpublic:CountdownTimer(std::function<void(const QString&)> updateCallback, int totalTime, QObject *parent = nullptr);void start();private:QTimer *timer;int remainingTime;std::function<void(const QString&)> updateCallback; // 回调函数代替直接 QLabel 操作void handleTimeout();
};#endif // COUNTDOWNTIMER_H
"countdownTimer.cpp"
#include "countdownTimer.h"CountdownTimer::CountdownTimer(std::function<void(const QString&)> updateCallback, int totalTime, QObject *parent) :QObject(parent), updateCallback(updateCallback), remainingTime(totalTime)
{timer = new QTimer(this);timer->setInterval(1000); // 设置定时器间隔connect(timer, &QTimer::timeout, this, &CountdownTimer::handleTimeout);
}void CountdownTimer::start()
{timer->start();
}void CountdownTimer::handleTimeout()
{if (remainingTime > 0) {// int minutes = remainingTime / 60000;int seconds = (remainingTime % (60000+1)) / 1000;// int milliseconds = remainingTime % 1000;// QString text = QString("%1:%2:%3")// .arg(minutes, 2, 10, QChar('0'))// .arg(seconds, 2, 10, QChar('0'))// .arg(milliseconds, 3, 10, QChar('0'));QString text = QString("%1").arg(seconds, 1, 10, QChar('0'));// QString text = QString("%1").arg(seconds, 2, 10, QChar('0'));//左边补0updateCallback(text); // 使用回调函数更新UIremainingTime -= 1000;} else {updateCallback("00:00:000"); // 通知结束timer->stop();}
}