timeupdatethread.cpp 724 B

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