multithreadingqtqt5qthreadqtimer

Timers cannot be stopped from another thread Qt


I am working on Qt application. There I am using two threads, one for the GUI and one for do the processing.

I have worker class which has QTimer as member class.

.h file:

#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 file

#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();
}

I can start the thread with no error. However when I close the application I am getting warning message.

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

If QTimer is child of worker class and it has been moved to thread why Qt is complaining about stopping it from different thread? Note: I have added logs to print thread id and it outputs same value in both cases:

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

Can someone please explain? I do not understand what it's happening here

Thanks in advance


Solution

  • I finally was able to fix the error by:

    1. Converting QTimer to pointer
    2. Adding slot stopWorker as suggested by @Amfasis
    3. In that slot not only stop QTimer but also delete it

    Thanks all