1.一个主界面(主线程),一个次线程,次线程通过信号向主线程传递递增变量,主线程将它显示出来
mythread.h
#include <QThread>
#include <QDebug>
class Mythread : public QThread
{
Q_OBJECT
public:
Mythread();
protected:
void run();
private:
int i;
signals:
void signal_add_int(QString);
};mythread.cpp
#include "mythread.h"
#include <QDebug>
Mythread::Mythread()
{
i = 0;
}
void Mythread::run()
{
while(1)
{
i++;
QString str = QString::number(i,10);
emit signal_add_int(str);
sleep(1);
qDebug()<<"run thread:" <<QThread::currentThreadId();
}
}
mainwindow.h
#include <QMainWindow>#include "mythread.h"namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{Q_OBJECTpublic:
explicit MainWindow(QWidget *parent = 0);~MainWindow();private:
Ui::MainWindow *ui;Mythread thread;private slots:void set_lineEdit_text(QString);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);connect(&thread,SIGNAL(signal_add_int(QString)),this,SLOT(set_lineEdit_text(QString)),Qt::QueuedConnection);connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(start_thread()));qDebug()<<"MainWindow:" <<QThread::currentThreadId();}MainWindow::~MainWindow()
{delete ui;}void MainWindow::set_lineEdit_text(QString str){ui->lineEdit->setText(str);qDebug()<<"from thread slot:" <<QThread::currentThreadId();}void MainWindow::start_thread(){thread.start();}打印结果:MainWindow: 3062654672 from thread slot: 3062654672 run thread: 3017550736 from thread slot: 3062654672 run thread: 3017550736 from thread slot: 3062654672 run thread: 3017550736 from thread slot: 3062654672结论:
主线程运行thread.start()后,次线程启动,进入到次线程中,次线程发送信号给主线程,主线程接收到该信号,进入槽函数,该槽函数也在主线程中运行。次线程的开始和结束都在run函数中开始和结束