想写个线程来不停处理接受到的数据,然后Qt5没发现完整的案例。
找了好多,都写得不明不白的,无从下手
给各位一个题目吧,最简单的计数器,100ms更新一次,给个能跑起来的demo……
//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
#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.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.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();
}
}