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

上代码:

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

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_


运行结果:

点击 按钮 operate 并没有执行

MySlotObject::slotOperat()函数;


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

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





版权声明:本文为yuzuyi2006原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。