gpt4 book ai didi

multithreading - 无法从另一个线程Qt停止计时器

转载 作者:行者123 更新时间:2023-12-03 13:16:55 25 4
gpt4 key购买 nike

我正在研究Qt应用程序。我在这里使用了两个线程,一个用于GUI,一个用于处理。

我有 worker 类(Class),其中有QTimer作为成员类(Class)。

.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是worker类的子级,并且已移到线程中,为什么Qt提示从另一个线程停止它?
注意:我添加了日志来打印线程ID,在两种情况下它输出相同的值:
worker thread  QThread(0x72fdf0)
timer thread QThread(0x72fdf0)

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

提前致谢

最佳答案

我终于可以通过以下方式解决错误:

  • 将QTimer转换为指针
  • 根据@Amfasis
  • 的建议添加slot stopWorker
  • 在该插槽中,不仅停止QTimer,还将其删除

  • 谢谢大家

    关于multithreading - 无法从另一个线程Qt停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53288644/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com