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();
}

你可能感兴趣的:(QT)