QT 多线程下信号和槽的使用

Qt的信号槽机制可以将任何继承自QObject类的对象捆绑在一起,使不同对象之间能相互通信。QThread继承自QObject,能够发射信号和定义槽函数

  • thread.h
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
#include <QString>

class Thread : public QThread
{
    Q_OBJECT
public:
    Thread(QObject *parent);
    virtual void run();

signals:
    void send(QString msg);
private:
};

#endif
  • thread.cpp
#include "thread.h"
#include <QDebug>

Thread::Thread(QObject *parent) :
    QThread(parent)
{

}
void Thread::run()
{
  msleep(100);
  //发送一个信号给主线程
  qDebug()<<"Thread id :" <<this->currentThreadId() << "is running";
  emit send(QString("thread"));
}
  • widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPainter>
#include "thread.h"

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();
    
public slots:
    void accept(QString msg);
    
private slots:
    void on_pushButton_clicked();
    
private:
    Ui::Widget *ui;
};
#endif // WIDGET_H
  • widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "thread.h"
#include <qdebug.h>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    t = new Thread(NULL);
    connect(t, SIGNAL(send(QString)), this, SLOT(accept(QString)),Qt::QueuedConnection);
}

Widget::~Widget()
{
    t->wait();
    delete ui;
}

void Widget::accept(QString msg)
{
	qDebug()<<tr("完成信号触发");
}
void Widget::on_pushButton_clicked()
{
     t->start();
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值