首页 新闻 会员 周边 捐助

Qt5 MovetoThread 怎么用?

0
悬赏园豆:20 [已关闭问题] 关闭于 2021-12-06 15:39

想写个线程来不停处理接受到的数据,然后Qt5没发现完整的案例。
找了好多,都写得不明不白的,无从下手

给各位一个题目吧,最简单的计数器,100ms更新一次,给个能跑起来的demo……

echo_lovely的主页 echo_lovely | 小虾三级 | 园豆:1546
提问于:2021-12-06 14:57
< >
分享
所有回答(1)
0

Worker.h

//tes.h
#ifndef TES_H
#define TES_H

#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QString>
#include <QObject>

class Worker: public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = 0);
    ~Worker();

    void start();
    void stop();
private:
    bool flag = true;

signals:
    void sig_finish(int i);

public slots:
    void slot_dowork();

};
#endif // TES_H

Worker.cpp


#include "Worker.h"

Worker::Worker(QObject *parent): QObject(parent)
{
    qDebug() << "worker()";
}

Worker::~Worker()
{
    qDebug() << "~worker()";
}

void Worker::start()
{
    flag = true;
}

void Worker::stop()
{
    flag = false;
}

void Worker::slot_dowork()
{
    int i = 0;
    while (flag) {
        i ++;
        QThread::msleep(500);
        emit sig_finish(i);//这个是通过信号&槽机制返回线程中的一些数据
    }
}

MainWindow头文件

//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "Worker.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void dowork();

private:
    Ui::MainWindow *ui;
    Worker *m_pworker;
    QThread *m_pthread;
    bool flag = false;

signals:
    void sig_dowork();

public slots:
    void slot_finish(int i);
private slots:
    void on_pushButton_clicked();
};

#endif // MAINWINDOW_H

MainWindow主体文件

//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    qDebug() << "mainwindow()";
    ui->setupUi(this);

    m_pworker = new Worker();
    m_pthread = new QThread();
    m_pworker->moveToThread(m_pthread);
    qDebug() << "start,thread id = " << QThread::currentThreadId();

    connect(m_pthread, &QThread::finished, m_pworker, &QObject::deleteLater);
    connect(this, SIGNAL(sig_dowork()), m_pworker, SLOT(slot_dowork()));
    connect(m_pworker, SIGNAL(sig_finish(int)), this, SLOT(slot_finish(int)));
}

MainWindow::~MainWindow()
{
    qDebug() << "~mainwindow()";
    delete ui;
    m_pthread->quit();
    m_pthread->wait();
}

void MainWindow::dowork()
{
    m_pthread->start();
    emit sig_dowork();
}

void MainWindow::slot_finish(int i)
{
    qDebug() << "finish,thread id = " << QThread::currentThreadId();
    qDebug() << "finish,thread id = " << i;
}
//按钮方法
void MainWindow::on_pushButton_clicked()
{
    this->flag = !this->flag;
    if (this->flag) {
        this->dowork();
    } else {
        m_pworker->stop();
    }
}

界面

echo_lovely | 园豆:1546 (小虾三级) | 2021-12-06 15:39
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册