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

 

转载于:https://www.cnblogs.com/stones-dream/p/9360363.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值