Thread1
myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QObject>
#include <QThread>
#include <QDebug>
class MyClass : public QObject
{
Q_OBJECT
public:
explicit MyClass(QObject *parent = 0);
~MyClass();
signals:
public slots:
//需要放在线程中工作的槽函数
void func(void);
};
#endif // MYCLASS_H
myclass.cpp
#include "myclass.h"
MyClass::MyClass(QObject *parent) : QObject(parent)
{
}
MyClass::~MyClass()
{
}
//需要放在线程中工作的槽函数
void MyClass::func(void){
while(1){
qDebug() << "子线程:" << QThread::currentThreadId();
QThread::sleep(1);
}
}
threaddialog.h
#ifndef THREADDIALOG_H
#define THREADDIALOG_H
#include <QDialog>
#include <myclass.h>
namespace Ui {
class ThreadDialog;
}
class ThreadDialog : public QDialog
{
Q_OBJECT
public:
explicit ThreadDialog(QWidget *parent = 0);
~ThreadDialog();
private:
Ui::ThreadDialog *ui;
QThread thread;//子线程
//MyClass* myobject;
MyClass myobject;//需要放在子线程工作的对象
};
#endif // THREADDIALOG_H
threaddialog.cpp
#include "threaddialog.h"
#include "ui_threaddialog.h"
ThreadDialog::ThreadDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ThreadDialog)
{
ui->setupUi(this);
qDebug() << "主线程:" << QThread::currentThreadId();
//myobject = new MyClass;
//myobject->moveToThread(&thread);
//connect(ui->pushButton,SIGNAL(clicked()),
// myobject,SLOT(func()));
//将myobject移动到子线程中
myobject.moveToThread(&thread);
//连接信号和槽函数(需要放在线程执行)
connect(ui->pushButton,SIGNAL(clicked()),
&myobject,SLOT(func()));
//开启子线程
thread.start();
}
ThreadDialog::~ThreadDialog()
{
delete ui;
}
Thread2
myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QThread>
#include <QDebug>
//继承QThread
class MyClass : public QThread
{
public:
MyClass();
~MyClass();
private:
//重写线程入口函数
void run(void);
};
#endif // MYCLASS_H
myclass.cpp
#include "myclass.h"
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}
//重写线程入口函数
void MyClass::run(void){
while(1){
qDebug() << "子线程:" << currentThreadId();
sleep(1);
}
}
threaddialog.h
#ifndef THREADDIALOG_H
#define THREADDIALOG_H
#include <QDialog>
#include <myclass.h>
namespace Ui {
class ThreadDialog;
}
class ThreadDialog : public QDialog
{
Q_OBJECT
public:
explicit ThreadDialog(QWidget *parent = 0);
~ThreadDialog();
private:
Ui::ThreadDialog *ui;
MyClass thread;//子线程对象
};
#endif // THREADDIALOG_H
threaddialog.cpp
#include "threaddialog.h"
#include "ui_threaddialog.h"
ThreadDialog::ThreadDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ThreadDialog)
{
ui->setupUi(this);
qDebug() << "主线程:" << QThread::currentThreadId();
//触发start()函数执行,开启子线程,run函数将在子线程执行
connect(ui->pushButton,SIGNAL(clicked()),
&thread,SLOT(start()));
}
ThreadDialog::~ThreadDialog()
{
delete ui;
}
main.cpp
#include "threaddialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ThreadDialog w;
w.show();
return a.exec();
}