Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ Qt向移动到线程的对象发出信号_C++_Qt_Signals Slots_Qthread - Fatal编程技术网

C++ Qt向移动到线程的对象发出信号

C++ Qt向移动到线程的对象发出信号,c++,qt,signals-slots,qthread,C++,Qt,Signals Slots,Qthread,为了通过设置标志(然后从线程内返回)来启动停止线程,我需要与它通信 线程是这样实现的 MyClass* obj = new MyClass(0); connect( this,SIGNAL( stop() ),obj, SLOT(stop())); emit stop(); // slot is called (qDebug output) MyThread = new QThread; obj->moveToThread(MyThread); connect( ... start

为了通过设置标志(然后从线程内返回)来启动停止线程,我需要与它通信

线程是这样实现的

MyClass* obj = new MyClass(0);
connect( this,SIGNAL( stop() ),obj, SLOT(stop()));
emit stop();    // slot is called (qDebug output)

MyThread = new QThread;
obj->moveToThread(MyThread);
connect( ... started() ... quit() ... finished() ... deleteLater() ...
....

emit stop();    // slot isn't called (qDebug output)
插槽还没有任何逻辑,它只使用qDebug()输出。 对象的创建和连接在主窗口方法中进行


不幸的是,我不知道我做错了什么:一旦对象移动到线程,插槽就不再运行了。

调试输出实际上是在线程完成其工作之后才发生的。 使用


解决了问题。

也许您只是忘记了复制/粘贴它,但是您缺少了一个
MyThread->start()
调用。另外,声明线程的行应该是
QThread*MyThread=new QThread(),但那可能只是一个打字错误

现在,在您的回答中,您说使用
Qt::DirectConnection
似乎已经解决了您的问题。但是,使用直接连接调用的slot只直接调用slot方法。slot方法正在运行,但它是从调用线程运行的(在那里发出
stop()
信号)。即使你的线程没有启动,这也会起作用。您真正想要的是通过
Qt::QueuedConnection
调用插槽。这将在工作线程的事件循环中放置一个事件,然后该事件将调用插槽。请注意,如果不指定,Qt将处理连接类型

如果排队连接不起作用,那么您可能正在用您的工作阻塞线程的事件循环。在您的工作方法中,您是否将控件传递回事件循环以允许它处理事件?或者它只是在
循环中运行,而
循环等待标志更改状态


此外,您的代码不会按原样编译/运行。我假设您已经在处理
QApplication
了,也就是说,在
main
函数中设置好所有内容后,调用
QApplication::exec()
。如果不调用
exec()
,则主事件循环将永远不会启动。

是否在第二个线程中运行事件循环?谢谢,没有回答。我很快会调查的。
connect( this, SIGNAL(stop()), obj, SLOT(stop()), Qt::DirectConnection);