创建界面工程后,在界面上拖两个按钮并添加对应的click槽,再添加一个MyThread类继承自QObject。
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class QThread;
class MyThread;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
signals:
void sig_recvMsg(QString msg);
public slots:
void slot_sendMsg(QString msg);
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
Ui::MainWindow *ui;
QThread *thread;
MyThread *myThread;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>
#include "mythread.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
thread = new QThread();
myThread = new MyThread();
myThread->moveToThread(thread);
connect(this, &MainWindow::sig_recvMsg, myThread, &MyThread::slot_recvMsg);
connect(myThread, &MyThread::sig_sendMsg, this, &MainWindow::slot_sendMsg);
}
MainWindow::~MainWindow()
{
delete ui;
if(thread) {
delete thread;
thread = nullptr;
}
if(myThread) {
delete myThread;
myThread = nullptr;
}
}
void MainWindow::slot_sendMsg(QString msg)
{
qDebug()<<__FUNCTION__<<" "<<msg<<" "<<QThread::currentThreadId();
thread->quit();
thread->wait();
}
void MainWindow::on_pushButton_clicked()
{
emit sig_recvMsg("222222222");
thread->start();
}
void MainWindow::on_pushButton_2_clicked()
{
myThread->slot_recvMsg("333333333");
}
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
class MyThread : public QObject
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
~MyThread();
signals:
void sig_sendMsg(QString msg);
public slots:
void slot_recvMsg(QString msg);
};
#endif // MYTHREAD_H
mythread.cpp
#include "mythread.h"
#include <QThread>
#include <QDebug>
MyThread::MyThread(QObject *parent) : QObject(parent)
{
qDebug()<<__FUNCTION__<<" "<<QThread::currentThreadId();
}
MyThread::~MyThread()
{
qDebug()<<__FUNCTION__<<" "<<QThread::currentThreadId();
}
void MyThread::slot_recvMsg(QString msg)
{
qDebug()<<__FUNCTION__<<" "<<msg<<" "<<QThread::currentThreadId();
emit sig_sendMsg("1111111111");
}
先后点击两个按钮,得到如下输出,threadId每此都会不同,不必参照下面的输出结果
MyThread::MyThread 0x21d0
MyThread::slot_recvMsg "222222222" 0x3238
MainWindow::slot_sendMsg "1111111111" 0x21d0
MyThread::slot_recvMsg "333333333" 0x21d0
MainWindow::slot_sendMsg "1111111111" 0x21d0
MyThread::~MyThread 0x21d0