您的位置:首页 > 其它

线程使用方法之moveToThread

2017-06-01 10:04 525 查看
widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
Q_OBJECT

public:
explicit Widget(QWidget *parent = 0);
~Widget();

private:
Ui::Widget *ui;

public slots:
void slot();
};

class ThreadWorker : public QObject
{
Q_OBJECT
public:
ThreadWorker(QObject* parent=0);

signals:
void sig();

public slots:
void slot();
};

#endif // WIDGET_H


widget.cpp

#include "widget.h"
#include "ui_widget.h"

#include <QThread>
#include <QDebug>

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);

qDebug() << "widget thread: " << thread()->currentThreadId();
}

Widget::~Widget()
{
qDebug() << "~Widget()";

delete ui;

}

void Widget::slot()
{
qDebug() << "Widget::slot()" << ", widget thread: " << thread()->currentThreadId();
}

ThreadWorker::ThreadWorker(QObject *parent) :
QObject(parent)
{

}

void ThreadWorker::slot()
{
qDebug() << "ThreadWorker::slot()" << ", ThreadWorker thread:" << QThread::currentThreadId();

emit sig();
}


main.cpp

#include "widget.h"
#include <QApplication>

#include <QDebug>

#include <QThread>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

qDebug() << "main thread: " << qApp->thread()->currentThreadId();;

Widget w;
w.show();

//方法2:moveToThread
ThreadWorker threadWorker;
QThread thread;
threadWorker.moveToThread(&thread);

QObject::connect(&threadWorker, SIGNAL(sig()), &w, SLOT(slot()));
QObject::connect(&thread, SIGNAL(started()), &threadWorker, SLOT(slot()) );
QObject::connect(&thread, SIGNAL(finished()), &threadWorker, SLOT(deleteLater()) );
thread.start();

return a.exec();
}


注意点:程序结束会提示信息 QThread: Destroyed while thread is still running
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: