QThread 使用MoveToThread方式 槽函数不执行 分享

上代码:

MainWindow.cpp

#include "MainWindow.h"  
#include   
#include   
#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();
    QThread *slotthread = new QThread(this);
    slotObj->moveToThread(slotthread);
    connect(this, SIGNAL(sigOperate()), slotObj, SLOT(slotOperat()));
    //slotthread->start();

    qDebug() << __FUNCTION__ << QThread::currentThreadId();
    setCentralWidget(p);
}

MainWindow::~MainWindow() {
    if (nullptr != slotObj)
    {
        delete slotObj;
        slotObj = nullptr;
    }


}

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



MainWindow.h

#include 
#include 

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;
};

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   
#include   
#include   
class MySlotObject : public QObject
{
    Q_OBJECT
public:
    MySlotObject(QObject* parent = 0);
    ~MySlotObject();

public slots:
void slotOperat();
};

#endif //_MY_SLOT_OBJECT_H_


运行结果:

点击 按钮 operate 并没有执行

MySlotObject::slotOperat()函数;


问题原因是:线程没有启动, 因此

MainWindow构造函数中需要加上 slotthread->start(); 

QThread 使用MoveToThread方式 槽函数不执行 分享_第1张图片



你可能感兴趣的:(Qt,c++,QThread,MoveToThread,槽还是不执行)