QT 多线程信号与槽(二)

一个主线程,一个次线程,主线程向次线程发送信号

mythread.h

#include <QThread>
#include <QDebug>
class Mythread : public QThread
{
    Q_OBJECT
public:
    Mythread();
protected:
    void run();
private:
 
 
public slots:
    void receive_main_signal(int);
};
mythread.cpp

#include "mythread.h"
#include <QDebug>
Mythread::Mythread()
{
    qDebug()<<"Mythread:" <<QThread::currentThreadId();
    //moveToThread(this);

}
 
 
void Mythread::run()
{
    qDebug()<<"run:" <<QThread::currentThreadId();
    exec();
}
void Mythread::receive_main_signal(int a)
{
    qDebug()<<"from MainWindow:" <<QThread::currentThreadId();
    qDebug()<<"i="<<a;
}
MainWindow.h
#include <QMainWindow>
#include "mythread.h"
namespace Ui {
    class MainWindow;
}
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private:
    Ui::MainWindow *ui;
    Mythread thread;
signals:
    void emit_signal_to_thread(int);
public slots:
    void start_thread();
};
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qDebug()<<"MainWindow:" <<QThread::currentThreadId();
    connect(this,SIGNAL(emit_signal_to_thread(int)),&thread,SLOT(receive_main_signal(int)));//主线程给次线程发消息
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(start_thread()));
}
MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::start_thread()
{
    thread.start();
    int i;
    for(i=0;i<10;i++)
    {
        emit emit_signal_to_thread(i);
        sleep(1);
    }
}
打印结果:
Mythread: 3063412432 
MainWindow: 3063412432 
from MainWindow: 3063412432 
i= 0 
run: 3018308496 
from MainWindow: 3063412432 
i= 1 
from MainWindow: 3063412432 
i= 2 
from MainWindow: 3063412432 
i= 3 
from MainWindow: 3063412432 
i= 4 
from MainWindow: 3063412432 
i= 5 
from MainWindow: 3063412432 
i= 6 
from MainWindow: 3063412432 
i= 7 
from MainWindow: 3063412432 
i= 8 
from MainWindow: 3063412432 
i= 9 
结论:主线程向子线程发送信号,子线程对应的槽函数实现还是在主线程中完成的。如何使子线程的槽函数在子线程中完成呢?可以将mythread.cpp中moveToThread(this)的//去掉,最后可以显示:
Mythread: 3064174288 
MainWindow: 3064174288 
run: 3019070352 
from MainWindow: 3019070352 
i= 0 
from MainWindow: 3019070352 
i= 1 
from MainWindow: 3019070352 
i= 2 
from MainWindow: 3019070352 
i= 3 
from MainWindow: 3019070352 
i= 4 
from MainWindow: 3019070352 
i= 5 
from MainWindow: 3019070352 
i= 6 
from MainWindow: 3019070352 
i= 7 
from MainWindow: 3019070352 
i= 8 
from MainWindow: 3019070352 
i= 9 
可见子线程的槽函数在新线程中运行了,没有出现在主线程中。但这种方法是被Bradley T. Hughes所唾弃的,所以还是用大家公认为比较对的方法吧。(见下篇)

你可能感兴趣的:(多线程,qt)