线程使用方法之moveToThread

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Y673582465/article/details/72828578

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

展开阅读全文

没有更多推荐了,返回首页