QThread 的moveToThread 结果并没有在子线程中运行

时间:2022-06-10 23:13:37

//<<---------------MainWindow.h文件内容------------------------>>

#include <QMainWindow>
#include <QPushButton>

class MySlotObject;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent);
~MainWindow();

signals:
void sigOperate();
private slots:
void onOperated();
private:
MySlotObject* slotObj;
QPushButton* operatButton;
};

//<<-------------------MainWindow.cpp文件内容---------------------- >>

#include "MainWindow.h"  
#include <QPushButton>
#include <QVBoxLayout>
#include "MySlotObject.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
operatButton = new QPushButton(tr("operate"), 0);
connect(operatButton, SIGNAL(clicked()), this, SLOT(onOperated()));

QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(operatButton);

QWidget *p = new QWidget;
p->setLayout(layout);

slotObj = new MySlotObject(this);
QThread *slotthread = new QThread;
slotObj->moveToThread(slotthread);
connect(this, SIGNAL(sigOperate()), slotObj, SLOT(slotOperat()));
slotthread->start();
qDebug() << __FUNCTION__ << QThread::currentThreadId();
setCentralWidget(p);
}

MainWindow::~MainWindow() {
}

void MainWindow::onOperated()
{
qDebug() << __FUNCTION__ << QThread::currentThreadId();
emit sigOperate();
}

//<<-------------------------------MySlotObject.cpp内容------------------------------->

#include "MySlotObject.h"


MySlotObject::MySlotObject(QObject* parent)
:QObject(parent)
{
}


MySlotObject::~MySlotObject()
{
}

void MySlotObject::slotOperat()
{
qDebug() << __FUNCTION__ << QThread::currentThreadId();
}



//<<----------------------------------MySlotObject.h内容------------------------------------->

#ifndef _MY_SLOT_OBJECT_H_
#define _MY_SLOT_OBJECT_H_

#include <QObject>
#include <QDebug>
#include <QThread>
class MySlotObject : public QObject
{
Q_OBJECT
public:
MySlotObject(QObject* parent = 0);
~MySlotObject();

public slots:
void slotOperat();
};

#endif //_MY_SLOT_OBJECT_H_




#endif //_MY_SLOT_OBJECT_H_

点击按钮operate 运行结果

QThread 的moveToThread  结果并没有在子线程中运行


QThread 的moveToThread  结果并没有在子线程中运行


发现结果不是想要的,问题的原因是

QThread 的moveToThread  结果并没有在子线程中运行


问题出现中 slotObj = new MySlotObject(this);  应该改slotObj = new MySlotObject();  //记得对象释放

再次运行:

QThread 的moveToThread  结果并没有在子线程中运行

这次运行正确了。