QT线程通信实例源码介绍,bool QObject::connect ( const QObject * sender, const char * signal, const QObject * receiver, const char * method,Qt::ConnectionType type = Qt::AutoConnection ) [static]
Qt支持6种连接方式,其中3中最主要:
Qt::DirectConnection(直连方式)
当信号发出后,相应的槽函数将立即被调用。emit语句后的代码将在所有槽函数执行完毕后被执行。(信号与槽函数关系类似于函数调用,同步执行)
Qt::QueuedConnection(排队方式)
当信号发出后,排队到信号队列中,需等到接收对象所属线程的事件循环取得控制权时才取得该信号,调用相应的槽函数。emit语句后的代码将在发出信号后立即被执行,无需等待槽函数执行完毕。(此时信号被塞到信号队列里了,信号与槽函数关系类似于消息通信,异步执行)
Qt::AutoConnection(自动方式)
Qt的默认连接方式,如果信号的发出和接收这个信号的对象同属一个线程,那个工作方式与直连方式相同;否则工作方式与排队方式相同。
还是贴点实例的代码吧
threadmananage.h 继承自QThread
#ifndef THREADMANAGE_H
#define THREADMANAGE_H
#include
class threadManage : public QThread
{
Q_OBJECT
public:
explicit threadManage(QObject *parent = 0);
//mythread test
void stop();
//extern int fileshare_client();
signals:
//这里制造一个名为Log的信号
void Log(int);
public slots:
protected:
//mythread test
void run();
private:
//mythread test
volatile bool stopped;//使用volatile可以使的它在任何时候保持最新值
};
#endif // THREADMANAGE_H
threadmananage.cpp
#include “threadmanage.h”
#include “mainwindow.h”
#include
#include
threadManage::threadManage(QObject *parent) :
QThread(parent)
{
stopped = false;//初始化为false
}
//mythread 停止进程
void threadManage::stop()
{
stopped = true;
}
//mythread test 运行进程
void threadManage::run()
{
#if 0
qreal i = 0;
while(!stopped)
{
qDebug()<<QString(“in myThread:%1″).arg(i++);
}
stopped = false;
#endif
#if 1
//发射一个Log信号,这样主线程就可以安全的对界面进行修改了
emit Log(int(12));
#endif
}
mainwindow.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
//这里制造一个名为Logw的回调(槽),这个回调会对界面的一个QT控件
void Logw(int);
}
mainwindow.cpp
#include “threadmanage.h” //线程管理
void MainWindow::Logw(int sMessage)
{
qDebug()<<112;
if(12 == sMessage)
{
QMessageBox::warning(this, tr(“警告!”), tr(“slot成功!”),QMessageBox::Yes);
}
}
//以下函数是一个界面按钮“on_pushButton_fileShare1_rec_ok_clicked”的“转到槽”的函数
int MainWindow::on_pushButton_fileShare1_rec_ok_clicked()
{
#if 1
QObject::connect(&threadManage_fileshare_rec, SIGNAL(Log(int)), this, SLOT(Logw(int)), Qt::QueuedConnection);//可以放在构造函数中
threadManage_fileshare_rec.start();//开启线程
ui->lineEdit_fileshare1_rec_ip->setText(tr(“mythread 运行中。。。”).trimmed());
#endif
}
//以下是“取消”按钮的“转到槽”函数
void MainWindow::on_pushButton_fileShare2_send_cancel_clicked()
{
#if 1
//mythread test
if(mythread.isRunning())
{
threadManage_fileshare_rec.stop();
ui->lineEdit_fileShare2_send_path->setText(tr(“mythread停止!”).trimmed());
}
#endif
}
#include //messagebox
#include //textstream数据流操作
#include
threadManage threadManage_fileshare_rec; //创建一个线程对象
//slot函数