如何在不同的 QThreads 中 运行 函数

How to run functions in different QThreads

如何 运行 在不同的 QThreads 中循环函数?我需要在不同的线程中 运行 因为如果我不这样做,循环就会中断。

如何让on_pushTurnOn_clicked在其他线程执行,pushTurnOn的循环即使在不同的线程也必须能够被on_pushTurnOff_clicked取消。

MainWindow.h代码:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
#include <QThread> //I don't know how to use it
#include <QTimer>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:

        void on_pushTurnOn_clicked();

        void on_pushTurnOff_clicked();

private:

QTimer *timerLoop;

};

#endif // MAINWINDOW_H

MainWindow cpp代码:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushTurnOn_clicked()
{
    timerLoop = new QTimer(this);
    timerLoop->setInterval(3000);
    timerLoop->setSingleShot(true);
    connect(timerLoop, SIGNAL(timeout()), 
    SLOT(on_pushTurnOn_clicked()));

    qDebug()<<"the loop was started";
    timerLoop->start(); //start the loop
}

void MainWindow::on_pushTurnOff_clicked()
{
    qDebug()<<"the loop was stoped";
    timerLoop->stop(); //stop the loop
}

我将从旁注开始。您在 on_pushTurnOn_clicked() 中为 timerLoop 分配的内存将由于没有重新分配而导致内存泄漏,即使它是单次计时器。您正在创建一个新的 QTimer 而不会破坏之前分配的一个。更好的方法是在构造函数中只分配一次内存,然后在 on_pushTurnOn_clicked().

中启动计时器

回到你的问题,你必须将你的 class 分成两部分,一个是你的 mainWindow,它有 on_pushTurnOn_clicked()on_pushTurnOff_clicked() 的位置,其他可能的 UI 元素和非密集型任务。

第二个 class 是一个工人,它包含 QTimer 以及实际工作量。所以你基本上会有这样的东西:

MainWindow.cpp:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //constructor
    ui->setupUi(this);
    this->worker = new Worker(); //object of WorkerClass type
    QThread *thread = new QThread();
    worker->moveToThread(thread);
    connect(this, SIGNAL(startOrStopTimerSignal(bool), worker, SLOT(startStopTimer(bool));
}
void MainWindow::on_pushTurnOn_clicked()
{
    if(Busy==1){
        qDebug()<<"Is busy!";
    }
    if(Busy==0){
    FuncaoLoop(RandomParameter1, RandomParameter2);
    }
//start the timer through a signal (timers need to be started in their own threads)
    emit startOrStopTimerSignal(true);
}

void MainWindow::on_pushTurnOff_clicked()
{
    emit startOrStopTimerSignal(false); //stop the timer
}

WorkerClass.h/.cpp:

WorkerClass::WorkerClass(QObject *parent) : QObject(parent)
{
    timerLoop= new QTimer(this);
    connect(timerLoop, SIGNAL(timeout()), this, SLOT(workLoad())); //timer connect to your actual task
}
void WorkerClass::startStopTimer(bool start)
{
    if (start)
        timerLoop->start();
    else
        timerLoop->stop();
}
WorkerClass::workLoad()
{
    //whatever task for your PLC
}

希望对您有所帮助。