Qt小例子学习82 - 从另一个线程停止QTimer
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>
#include <QTimer>
class Worker : public QObject
{
Q_OBJECT
public:
Worker();
private:
QTimer t;
public slots:
void process();
void startWorker();
void stopProcess();
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
QThread workerThread;
Worker wt;
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include <QDebug>
#include <iostream>
Worker::Worker() : t(this)
{
connect(&t, &QTimer::timeout, this, &Worker::process);
}
void Worker::process() { std::cout << "triggering timer" << std::endl; }
void Worker::startWorker() { t.start(1000); }
void Worker::stopProcess()
{
QMetaObject::invokeMethod(&t, "stop", Qt::QueuedConnection);
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
wt.moveToThread(&workerThread);
connect(&workerThread, &QThread::started, &wt, &Worker::startWorker);
connect(&workerThread, &QThread::finished, &workerThread,
&QObject::deleteLater);
workerThread.start();
}
MainWindow::~MainWindow()
{
wt.stopProcess();
workerThread.quit();
workerThread.wait();
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}