本文粗略整理一下关于Qt 多线程中MoveToThread()的用法,以便回顾。
Qt中想实现多线程技术是很方便的,只需要子类化QThread且重新实现它的run()即可。可参阅《C++ GUI Qt4编程》第二版的第十四章。
MoveToThread()也能用于实现多线程,见代码:
#include "DBMoveToThread.h"
#include <QThread>
DBMoveToThread::DBMoveToThread(QObject *parent) :
QObject(parent)
{
DBThread *thread = new DBThread;
this->moveToThread(thread);
thread->start();
}
void DBMoveToThread::callWork()
{
qDebug()<<"callWork : "<<QThread::currentThread();
}
void DBMoveToThread::slotWork1()
{
qDebug()<<"slotWork1 : "<<QThread::currentThread();
}
void DBMoveToThread::slotWork2()
{
qDebug()<<"slotWork2 : "<<QThread::currentThread();
}
void DBMoveToThread::slotWork3()
{
qDebug()<<"slotWork3 : "<<QThread::currentThread();
}
定义了一个继承自QObject的类:DBMoveToThread,子类化QThread类,然后将DBMoveToThread对象(this)丢进thread中,thread->start();语句就是开启一个线程,相当于《C++ GUI Qt4编程》中说的run()函数。这样之后,DBMoveToThread对象中的槽函数就会在非GUI线程中运行。
此处生成了3个对象:
work(用于调用callwork()函数,预计在GUI线程中运行)
work12(调用槽函数:slotwork1(),slotwork2(),预计在同一个线程中运行)
work3(调用槽函数:slotwork3(),预计在另外一个线程中运行)
调用slot函数的代码如下:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
work = new DBMoveToThread;
work12 = new DBMoveToThread;
work3 = new DBMoveToThread;
connect(ui->callButton,SIGNAL(clicked()),this,SLOT(maincall()));
connect(ui->slot1Button,SIGNAL(clicked()),work12,SLOT(slotWork1()),Qt::QueuedConnection);
connect(ui->slot2Button,SIGNAL(clicked()),work12,SLOT(slotWork2()),Qt::QueuedConnection);
connect(ui->slot3Button,SIGNAL(clicked()),work3,SLOT(slotWork3()),Qt::QueuedConnection);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::maincall()
{
work->callWork();
}
class DBThread是个空架子,主要是希望这个类能实现多线程:继承自QThread,.h代码如下:
#ifndef DBTHREAD_H
#define DBTHREAD_H
#include <QThread>
class DBThread : public QThread
{
Q_OBJECT
public:
explicit DBThread(QObject *parent = 0);
private:
signals:
public slots:
};
#endif // DBTHREAD_H
程序运行之后观察调试信息,和预计看相符否。
点击按钮 次序call---->slot_1---->slot_2---->slot_3
输出见附图(图上房了,在顶部):
callwork() 直接调用-----------处于GUI线程中
slotwork1,2()是调用的槽函数,对象是work12-------------新的线程中
slotwork3()是调用的槽函数,对象是work3-------------另外一个线程中