【Qt】QThread::moveToThread

本文展示了Qt中如何使用QThread实现多线程,并通过moveToThread方法将对象从主线程迁移到子线程,同时演示了在子线程中执行不同槽函数的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

myobject.h

#ifndef MYOBJECT
#define MYOBJECT
#include <QObject>
#include <QThread>
#include <QDebug>
#include <QApplication>
class MyObject:public QObject
{
    Q_OBJECT
public:
    MyObject(){}
    ~MyObject(){}

public slots:
    void first()
    {
        qDebug() << QThread::currentThreadId();

    }

    void second()
    {
        int i = 0;
        while(true)
        {
            if(i++ < 10)
                qDebug() << QThread::currentThreadId() << "second()";
            else
                break;
        }

    }

    void three()
    {

        for(int i = 0; i< 20000; ++i)
        {
            qDebug() <<QThread::currentThreadId()<< " -> three -> " << i;
            //qApp->processEvents();
        }
    }
};


#endif // MYOBJECT


dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include "myobject.h"
class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = 0);
    ~Dialog();

private:
    MyObject * my;
};

#endif // DIALOG_H
dialog.cpp

#include "dialog.h"
#include <QPushButton>
#include <QVBoxLayout>
#include "myobject.h"
Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
{
    this->setWindowTitle("moveToThread 事例");
    qDebug() << "main" << QThread::currentThreadId();
    my = new MyObject;

    QPushButton *button1 = new QPushButton("1");
    QPushButton *button2 = new QPushButton("2");
    QPushButton *button3 = new QPushButton("3");

    QHBoxLayout *layout = new QHBoxLayout;

    layout->addWidget(button1);
    layout->addWidget(button2);
    layout->addWidget(button3);

    this->setLayout(layout);

    connect(button1,SIGNAL(clicked(bool)),my,SLOT(first()));
    connect(button2,SIGNAL(clicked(bool)),my,SLOT(second()));
    connect(button3,SIGNAL(clicked(bool)),my,SLOT(three()));

    QThread *thread = new QThread;
    my->moveToThread(thread);
    connect(thread,SIGNAL(finished()),my,SLOT(deleteLater()));
    connect(thread,SIGNAL(finished()),thread,SLOT(deleteLater()));
    thread->start();
}

Dialog::~Dialog()
{

}

main.cpp

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

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();

    return a.exec();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值