首页 > 解决方案 > 定时器不能从另一个线程 Qt 停止

问题描述

我正在开发 Qt 应用程序。在那里我使用了两个线程,一个用于 GUI,一个用于处理。

我有以 QTimer 作为成员类的工人阶级。

.h 文件:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTimer>
#include <QThread>

class Worker : public QObject
{
  Q_OBJECT
 public:
  Worker();
  QTimer t;
 public slots:
  void process();
  void startWorker();
};

namespace Ui {
 class MainWindow;
}

class MainWindow : public QMainWindow
{
  Q_OBJECT

  public:
   explicit MainWindow(QWidget *parent = nullptr);
   ~MainWindow();

 private:
   QThread workerThread;
   Worker wt;
 };

 #endif // MAINWINDOW_H

.cpp 文件

#include "mainwindow.h"
#include <QDebug>
#include <iostream>

Worker::Worker() : t(this)
{
 connect(&t, SIGNAL(timeout()), this, SLOT(process()));
}

void Worker::process()
{
  std::cout << "triggering timer" << std::endl;
}

void Worker::startWorker()
{
  t.start(1000);
}

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent)
{
  wt.moveToThread(&workerThread);
  qDebug() << "worker thread " << wt.thread();
  qDebug() << "timer thread " << wt.t.thread();
  connect(&workerThread, SIGNAL(started()), &wt, SLOT(startWorker()));
  connect(&workerThread, &QThread::finished, &workerThread, &QObject::deleteLater);
  workerThread.start();
}

MainWindow::~MainWindow()
{
 workerThread.quit();
 workerThread.wait();
}

我可以毫无错误地启动线程。但是,当我关闭应用程序时,我会收到警告消息。

QObject::killTimer: Timers cannot be stopped from another thread 
QObject::~QObject: Timers cannot be stopped from another thread

如果 QTimer 是工人阶级的孩子并且它已被移至线程,为什么 Qt 抱怨从不同的线程停止它?注意:我已添加日志以打印线程 ID,并且在两种情况下都输出相同的值:

worker thread  QThread(0x72fdf0)
timer thread  QThread(0x72fdf0)

有人可以解释一下吗?我不明白这里发生了什么

提前致谢

标签: multithreadingqtqt5qthreadqtimer

解决方案


我终于能够通过以下方式修复错误:

  1. 将 QTimer 转换为指针
  2. 按照@Amfasis 的建议添加 slot stopWorker
  3. 在那个插槽中不仅停止 QTimer 还要删除它

谢谢大家


推荐阅读