Qt moveToThread槽未调用

时间:2014-08-14 12:24:55

标签: c++ qt signals qthread slot

我有一个班级Manager

class Manager : public QThread 
{
    Q_OBJECT
    public:
    Manager();
    void run()
    {
        taskB = new TaskB();
        taskA = new TaskA();
        connect(taskA, SIGNAL(signalOk()), taskB, SLOT(onSignalOk()));
        connect(taskA, SIGNAL(moveOk()), taskB, SLOT(onMoveOk()));
        connect(taskB, SIGNAL(signal()), taskA, SLOT(onSignal()));
        connect(taskB, SIGNAL(moveToThreadSignal(QThread*)), taskA, SLOT(onMoveToThread(QThread*)));
        connect(this, SIGNAL(runSignal()), taskB, SLOT(onRun()));
        emit runSignal();
    }
    TaskA* taskA;
    TaskB * taskB;
    signals:
    void runSignal();
    };

我还有这样的课程TaskA

class TaskA : public QObject
{
    Q_OBJECT
    public:
    TaskA();
    void run()
    {
        std::cout << "[INFO] : Task run: " << QThread::currentThreadId() << std::endl;
        emit signalOk();
    }
    public slots:
    void onSignal()
    {
        run();
    }
    void onMoveToThread(QThread * t)
    {
        std::cout << "[INFO] : Task A after move to thread: " << QThread::currentThreadId() << std::endl;
        this->moveToThread(t);
        std::cout << "[INFO] : Task A after move to thread: " << QThread::currentThreadId() << std::endl;
        emit moveOk();
    }
    signals:
    void signalOk();
    void moveOk();
};

我还有像这样的课程TaskB

class TaskB : public QObject
{
    Q_OBJECT
    public:
    TaskB();
    void run()
    {
        std::cout << "[INFO] : TaskB run: " << QThread::currentThreadId() << std::endl;
        emit signal();
    }
    signals:
    void signal();
    void moveToThreadSignal(QThread* t);
    public slots:
    void onSignalOk()
    {
        std::cout << "[INFO] : TaskB onSignalOk : " << QThread::currentThreadId() << std::endl;
    }
    void onMoveOk()
    {
        std::cout << "[INFO] : TaskB onMoveOk: " << QThread::currentThreadId() << std::endl;
        run();
    }
    void onRun()
    {
        std::cout << "[INFO] : TaskB emit MoveToThreadSignal: " << QThread::currentThreadId() << std::endl;
        thread = new QThread();
        thread->start();
        emit moveToThreadSignal(thread);
    }
    private:
    QThread * thread;
};

当我用:

启动管理器时
  

经理* _manager =新经理();

     

_manager-&GT;开始();

onSignalOk()的广告TaskB未被调用。

我认为问题原因是我连接信号时的默认参数Qt::AutoConnection,但我不明白。

1 个答案:

答案 0 :(得分:1)

我建议首先不要继承QThread;它的名称具有误导性,因为它更像是一个线程管理器。在我看来,继承QThread的唯一原因是你想改变Qt管理线程的方式。

相反,只需从QObject继承并将对象移动到新线程。这样做的好处是能够将多个对象移动到一个新线程,而不必在继承QThread时为每个对象创建一个单独的线程。