这回写被大家认可的方法,继承QObject。还是主线程向子线程发信号,子线程接收信号,槽函数在新线程中运行。
mythread.h
#include <QThread>
#include <QDebug>
class Mythread : public QThread
{
Q_OBJECT
public:
Mythread();
protected:
void run();
private:
signals:
void MyThreadSignal();
public slots:
void MyThreadSlot();
};
mythread.cpp
#include "mythread.h"
#include <QDebug>
Mythread::Mythread()
{
qDebug()<<"Mythread:" <<QThread::currentThreadId();
}
void Mythread::run()
{
qDebug()<<"run:" <<QThread::currentThreadId();
exec();
}
void Mythread::MyThreadSlot()
{
qDebug()<<"from MainWindow:" <<QThread::currentThreadId();
}
myobject.h
#include <QObject>
class Myobject : public QObject
{
Q_OBJECT
public:
explicit Myobject(QObject *parent = 0);
signals:
void MyObjectSignal();
public slots:
void MyObjectSlot();
};
myobject.cpp#include "myobject.h"
#include<QDebug>
#include<QThread>
Myobject::Myobject(QObject *parent) :
QObject(parent)
{
emit MyObjectSignal();
}
void Myobject::MyObjectSlot()
{
qDebug()<<"MyObjectSlot:" <<QThread::currentThreadId();
}
mainwindow.h#include <QMainWindow>
#include "myobject.h"
#include "mythread.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void MainWindowSlot();
signals:
void MainWindowSignal();
private:
Ui::MainWindow *ui;
Myobject q_myObj;
Mythread thread;
};
mainwindow.cpp#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(this,SIGNAL(MainWindowSignal()),&q_myObj,SLOT(MyObjectSlot()),Qt::QueuedConnection);//主线程给子线程发信号
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(MainWindowSlot()));
q_myObj.moveToThread(&thread);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::MainWindowSlot()
{
thread.start();
emit MainWindowSignal();
}
最后打印:[root@localhost thread_test2]# ./thread_test2
Mythread: 3064583888 run: 3040099216 MyObjectSlot: 3040099216
看见没?MyObjectSlot和run的线程ID是一样的,说明在子线程中运行了。