一、信号与槽的实现代码如下
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mythread.h"
#include <QtDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//工作线程--->UI线程发送数据
WorkThread* thread1=new class WorkThread;
connect(thread1, SIGNAL(TestSignal(int)), this, SLOT(DisplayMsg(int)));
thread1->start();
//ui线程--->工作线程发送数据
UserThread* thread2=new class UserThread;
connect(this, SIGNAL(UiThreadSignal(int)), thread2, SLOT(UserThreadDisplayMsg(int)));
thread2->start();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
}
void MainWindow::on_pushButton_2_clicked()
{
emit UiThreadSignal(8);//发送信号
}
void MainWindow::on_pushButton_3_clicked()
{
}
//槽函数
void MainWindow::DisplayMsg(int n)
{
qDebug()<<QString::asprintf("DisplayMsg=%d",n);
}
二、线程类实现 .cpp
#include "mythread.h"
#include <QtDebug>
WorkThread::WorkThread()
{
}
void WorkThread::run()
{
qDebug()<<QString::asprintf("===>WorkThread");
// qDebug()<<n<<n<<n<<n<<n<<n<<n<<n;
int n=0;
while(true)
{
// qDebug()<<QString::asprintf("Thread=%d",1);
msleep(1000);
if(++n>=100)break;
emit TestSignal(n); //工作线程--->UI线程发送信号(信号与槽通信方式实现)
}
}
UserThread::UserThread()
{
}
//槽函数接收 UI线程下发的数据
void UserThread::UserThreadDisplayMsg(int n)
{
qDebug()<<QString::asprintf("UserThreadDisplayMsg=%d",n);
}
void UserThread::run()
{
qDebug()<<QString::asprintf("===>WorkThread");
// qDebug()<<n<<n<<n<<n<<n<<n<<n<<n;
int n=0;
while(true)
{
//qDebug()<<QString::asprintf("Thread=%d",2);
msleep(500);
if(++n>=100)break;
}
}
三、线程类实现 .h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class WorkThread : public QThread
{
Q_OBJECT
public:
WorkThread();
signals:
void TestSignal(int);
protected:
void run();
};
class UserThread : public QThread
{
Q_OBJECT
public:
UserThread();
private slots:
void UserThreadDisplayMsg(int);
protected:
void run();
};
#endif // MYTHREAD_H
四、运行如下
日志如下:
"UserThreadDisplayMsg=8"
"UserThreadDisplayMsg=8"
"DisplayMsg=2"
"UserThreadDisplayMsg=8"
"UserThreadDisplayMsg=8"
"UserThreadDisplayMsg=8"
"UserThreadDisplayMsg=8"
"DisplayMsg=3"
"DisplayMsg=4"
"DisplayMsg=5"
"DisplayMsg=6"
"DisplayMsg=7"
"DisplayMsg=8"
"DisplayMsg=9"
"DisplayMsg=10"
"DisplayMsg=11"
"DisplayMsg=12"
"DisplayMsg=13"
"DisplayMsg=14"
"DisplayMsg=15"