gpt4 book ai didi

multithreading - QObject::killTimer:计时器不能从另一个线程停止

转载 作者:行者123 更新时间:2023-12-03 13:16:57 25 4
gpt4 key购买 nike

我在我的 MainWindow 中有一个 QGraphicsView,它是我在我的 Ui 中创建的(当然是使用基本线程),我想设置一个 QGraphicsScene 来自另一个线程。

所以在 MainWindow 的构造函数中我有:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
...
connect(this,&MainWindow::graphSceneSignal,this,&MainWindow::graphSceneSlot);
...
QFuture<void> future;
future = QtConcurrent::run(this,&MainWindow::generateGraph);
...
}

MainWindow::generateGraph 中我有:

void MainWindow::generateGraph()
{
...
QPixmap p("myPix.png");
QGraphicsScene* scene = new QGraphicsScene();
scene->addPixmap(p);
emit graphSceneSignal(scene);
...
}

MainWindow::graphSceneSlot 中有:

void MainWindow::graphSceneSlot(QGraphicsScene* scene)
{
ui->graph_graphicsView->setScene(scene);
ui->graph_graphicsView->show();
}

但是我想解决这个警告:

QObject::killTimer: Timers cannot be stopped from another thread

那怎么办?

更新

我可以通过移动来解决这个问题:

QPixmap p("myPix.png");
QGraphicsScene* scene = new QGraphicsScene();
scene->addPixmap(p);

进入 MainWindow::graphSceneSlot

最佳答案

您收到此警告的原因是因为您创建的场景仍然“存在于”创建它的并发线程中。这意味着它无法从主线程中得到正确的“控制”。

Threads and QObjects

为了让您的代码正常运行,图形场景必须从并发线程“移动”到主线程。这可以通过使用 QObject::moveToThread 来完成:

void MainWindow::generateGraph()
{
...
QPixmap p("myPix.png");
QGraphicsScene* scene = new QGraphicsScene();
scene->addPixmap(p);
scene->moveToThread(this->thread()); //this line here does the trick
emit graphSceneSignal(scene);
...
}

您绝对应该阅读更多关于 Qt 中的线程和对象的内容。此链接会将您带到文档,其中对其进行了更详细的解释:Threads and QObjects

关于multithreading - QObject::killTimer:计时器不能从另一个线程停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50246310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com