multithreading - 定时器不能从另一个线程 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)
有人可以解释一下吗?我不明白这里发生了什么
提前致谢
解决方案
我终于能够通过以下方式修复错误:
- 将 QTimer 转换为指针
- 按照@Amfasis 的建议添加 slot stopWorker
- 在那个插槽中不仅停止 QTimer 还要删除它
谢谢大家
推荐阅读
- xml - 如何排序和获取最小开始日期(XSLT)
- python-3.x - 算法的效率 - 所有字符串元素都是唯一的
- html - 我的 iframe 视频周围不需要的黑色背景
- angular - Angular 9:错误 NG2003:没有适合类“DataService”的参数“url”的注入令牌。找到字符串
- google-apps-script - 发布 G Suite 插件:部署包含一个空的主机列表
- java - JavaFX stackpane未对齐的孩子
- byte-buddy - 在这种情况下,为什么 ByteBuddy 将方法委托路由到“错误”的方法?
- javascript - 用于 HTML 中动态下拉列表的 JavaScript onchange 事件
- jquery-ui-draggable - 我们如何将一个 ui.draggable 附加到一个目标上,将整个可拖动元素保留在它的位置?
- r - 在 R 中查找行方差