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