Qt中线程跟信号槽的关系
Qt中有方便的信号和槽函数来完成我们各个类之间的调用。其中关于对象在线程中信号和槽的执行方式是值得瞧瞧的。
这里我做了一点实验。说明请看代码注解和qDebug输出
主窗口(这里介绍了各种连接信号方式)
#include "widget.h"#include "ui_widget.h"#include "mythread.h"#include "obj.h"Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget){ ui->setupUi(this); thread = new MyThread(); obj = new Obj(); obj->moveToThread(thread); //注意 这句是移动对象到一个线程中,即他的槽执行都在这个指定的线程中 connect(ui->pushButton,SIGNAL(clicked()),obj,SLOT(getSignaled())); //默认Qt::AutoConnection 如果在同一线程则是DirectConnection,不同则是QueuedConnection //connect(ui->pushButton,SIGNAL(clicked()),obj,SLOT(getSignaled()),Qt::QueuedConnection); //在对象的当前线程中执行,并且是按照队列顺序执行。当当前线程停止,就会等待下一次启动线程时再按队列顺序执行 //connect(ui->pushButton,SIGNAL(clicked()),obj,SLOT(getSignaled()),Qt::DirectConnection); //这句不管理有没有线程都直接执行了 //connect(ui->pushButton,SIGNAL(clicked()),obj,SLOT(getSignaled()),Qt::BlockingQueuedConnection); //(必须信号和曹在不同线程中,否则直接产生死锁)这个是完全同步队列只有槽线程执行完才会返回,否则发送线程也会等待,相当于是不同的线程可以同步起来执行 //connect(ui->pushButton,SIGNAL(clicked()),obj,SLOT(getSignaled()),Qt::UniqueConnection); //跟默认工作方式相同,只是不能重复连接相同的信号和槽 //connect(ui->pushButton,SIGNAL(clicked()),obj,SLOT(getSignaled()),Qt::AutoCompatConnection); //这个是为了连接QT4 到QT3的信号槽机制兼容方式,工作方式跟Qt::AutoConnection一样 thread->start();}Widget::~Widget(){ delete ui;}void Widget::on_stopBtn_clicked(){ thread->terminate();}void Widget::on_pushButton_2_clicked(){ delete thread;}void Widget::on_pushButton_3_clicked(){ obj->getCall();}void Widget::on_pushButton_4_clicked(){ thread->start();}
?线程对象
#include "mythread.h"#include <QDebug>MyThread::MyThread(QObject *parent) : QThread(parent){ this->connect(this,SIGNAL(destroyed()),this,SLOT(myDestroyed())); this->connect(this,SIGNAL(finished()),this,SLOT(myFinished())); this->connect(this,SIGNAL(started()),this,SLOT(myStarted())); this->connect(this,SIGNAL(terminated()),this,SLOT(myTerminated()));}void MyThread::myTerminated(){ qDebug() << tr("线程停止了");}void MyThread::myStarted(){ qDebug() << tr("线程开始了");}void MyThread::myDestroyed(){ qDebug() << tr("线程对象删除了");}void MyThread::myFinished(){ qDebug() << tr("线程完成了");}
?普通对象(用于信号和槽接收)
#include "obj.h"#include <QDebug>Obj::Obj(QObject *parent) : QObject(parent), call_num(0){}void Obj::getSignaled(){ call_num ++; qDebug()<< "有信号过来了"; qDebug()<< "call num" << call_num;}void Obj::getCall(){ call_num ++; qDebug()<< "有调用过来了"; qDebug()<< "call num" << call_num;}
?代码附上
最后提示,建议试试点击各种按钮,对应输出来看