QT 继承 Qobject实现多线程
原创
©著作权归作者所有:来自51CTO博客作者蒋程扬的部落格的原创作品,请联系作者获取转载授权,否则将追究法律责任
Qt实现多线程的方法有很多种,不过通过继承Qobject这一种方法可以使用信号与槽函数与线程间进行通讯:
一,创建自己的继承Qobject的线程类
connect_thread.h:
#ifndef CONNECT_THREAD_H
#define CONNECT_THREAD_H
#include <QObject>
#include <QThread>
class connect_thread : public QObject
{
Q_OBJECT
public:
explicit connect_thread(QObject *parent = 0);
void closeThread();
signals:
protected:
public slots:
//开启线程的槽函数
void startThreadSlot();
private:
bool isStop;
};
#endif // CONNECT_THREAD_H
connect_thread.cpp:
#include "connect_thread.h"
#include <iostream>
#include <QUdpSocket>
#include <QDebug>
using namespace std;
connect_thread::connect_thread(QObject *parent)
:QObject(parent)
{
}
void connect_thread::closeThread()
{
isStop = true;
}
//这个函数写要循环运行的代码段
void connect_thread::startThreadSlot()
{
isStop = false;
while (1)
{
if(isStop)
return;
qDebug()<<"MyThread::startThreadSlot QThread::currentThreadId()=="<<QThread::currentThreadId();
QThread::sleep(1);
`在这里插入代码片`}
}
主函数;
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "connect_thread.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
connect_thread *th;
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QThread *server_th = new QThread(); //xianchengrongqi
th = new connect_thread;
th->moveToThread(server_th); //zhuanyi
connect(server_th,SIGNAL(started()),th,SLOT(startThreadSlot())); //开启线程槽函数
server_th->start(); //开启多线程槽函数
qDebug()<<"mainWidget QThread::currentThreadId()=="<<QThread::currentThreadId();
}
其中: 先使用QThread创建一个多线程容器:QThread *server_th = new QThread();
然后再新建自己的类: th = new connect_thread;
将自己的类移动到线程容器内: th->moveToThread(server_th);
连接QThread的开启线程信号,当线程开启时运行自己写的代码段: connect(server_th,SIGNAL(started()),th,SLOT(startThreadSlot())); //开启线程槽函数
开启线程:server_th->start(); //开启多线程槽函数
QThread *server_th = new QThread(); //xianchengrongqi
th = new connect_thread;
th->moveToThread(server_th); //zhuanyi
connect(server_th,SIGNAL(started()),th,SLOT(startThreadSlot())); //开启线程槽函数
server_th->start(); //开启多线程槽函数
qDebug()<<"mainWidget QThread::currentThreadId()=="<<QThread::currentThreadId(); #打印主线程号