timeupdatethread.cpp 725 B

12345678910111213141516171819202122
  1. #include "timeupdatethread.h"
  2. #include <QTimer>
  3. TimeUpdateThread::TimeUpdateThread(QObject *parent) : QThread(parent) {}
  4. void TimeUpdateThread::run() {
  5. QTimer timer;
  6. connect(&timer, &QTimer::timeout, [this]() {
  7. QDateTime currentDateTime = QDateTime::currentDateTime();
  8. QString currentTimeString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
  9. emit timeUpdated(currentTimeString);
  10. });
  11. timer.start(1000);
  12. // 初始化时立即更新一次时间
  13. QDateTime currentDateTime = QDateTime::currentDateTime();
  14. QString currentTimeString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
  15. emit timeUpdated(currentTimeString);
  16. exec(); // 启动线程的事件循环
  17. }