这是在ImageView
中调用的:
thread A
在此之前,连接和接收器创建发生:
void MainApplication::notify()
{
emit mySignal();
QThread::currentThread()->sleep(5);
}
期望:在// thread A
void MainApplication::init()
{
receiver->moveToThread(threadB);
connect(this,
&MainApplication::mySignal,
receiver,
&Receiver::onMySignal,
Qt::QueuedConnection);
}
上调用广告位Receiver::onMySignal()
现实:当发出thread B
睡眠时,不会调用slot。
P.S。:当发出信号时,我100%确定thread A
的事件循环正在运行。
答案 0 :(得分:1)
要处理此问题,您需要通过调用
运行一次事件队列QCoreApplication::processEvents();
这将触发处理来自线程的所有入队事件。
答案 1 :(得分:1)
实际上它应该是。以下简单示例可以正常工作。
class SenderObj : public QObject
{
Q_OBJECT
signals:
void happened();
public:
void triggerSignal() {
qDebug() << "Emitting 'happened'";
emit happened();
qDebug() << "Emitted 'happened'";
QThread::currentThread()->sleep(5);
}
};
class ReceiverObj : public QObject
{
Q_OBJECT
public slots:
void doSomething() {
qDebug() << "SLOT called in " << QThread::currentThread();
}
};
// In my MainWindow :
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
auto thread = new QThread(this);
thread->start();
m_senderObj = new SenderObj;
m_receiverObj = new ReceiverObj;
m_receiverObj->moveToThread(thread);
connect(m_senderObj, &SenderObj::happened, m_receiverObj, &ReceiverObj::doSomething);
}
void MainWindow::on_pushButton_clicked()
{
m_senderObj->triggerSignal();
}
当我单击按钮时立即发出信号,第二个线程立即执行插槽,我的主线程(MainWindow)被冻结5秒。