QT多线程简单例子

在Qt中实现多线程,除了使用全局变量。还可以使用信号/槽机制。

以下例子使用信号/槽机制。

功能: 在主线程A界面上点击按钮,然后对应开起一个线程B。线程B往线程A发送一个字符串,线程A打印出来。

1、工程文件目录

2、thread.h 和thread.cpp

#ifndef THREAD_H
#define THREAD_H
#include<QThread>
#include<QString>
 
class Thread : public QThread
{
    Q_OBJECT
public:
    Thread();
    virtual void run();
    void stop();
signals:
    
    void send(QString msg);
private:
 
};
 
#endif // THREAD_H
#include "thread.h"
 
Thread::Thread()
{
 
}
void Thread::run()
{
    //发送一个信号给主线程
    emit send(QString("thread"));
}

3、widget.h和widget.cpp

#ifndef WIDGET_H
#define WIDGET_H
 
#include <QWidget>
#include"thread.h"
 
 
namespace Ui {
class Widget;
}
 
class Widget : public QWidget
{
    Q_OBJECT
 
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
 
    void text();
public slots:
    void accept(QString msg);
 
private slots:
    void on_pushButton_clicked();
 
private:
    Ui::Widget *ui;
    Thread thread;
};
 
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
#include<QDebug>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    QObject::connect(&thread, SIGNAL(send(QString)), this, SLOT(accept(QString)));
   // thread.start();
}
 
Widget::~Widget()
{
    delete ui;
}
void Widget::accept(QString msg)
{
    qDebug()<<msg;
}
 
 
void Widget::on_pushButton_clicked()
{
    thread.start();
}

4、主函数

#include "widget.h"
#include <QApplication>
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
 
    return a.exec();
}

转自:https://blog.csdn.net/qq_33850438/article/details/78482935

猜你喜欢

转载自www.cnblogs.com/stones-dream/p/9360363.html