QObject::killTimer:无法从另一个线程停止计时器

mor*_*adi 2 qt multithreading qtconcurrent qgraphicsview

我有一个QGraphicsViewMainWindow我的 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);
...
}
Run Code Online (Sandbox Code Playgroud)

我有MainWindow::generateGraph

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

里面MainWindow::graphSceneSlot有:

void MainWindow::graphSceneSlot(QGraphicsScene* scene)
{
    ui->graph_graphicsView->setScene(scene);
    ui->graph_graphicsView->show();
}
Run Code Online (Sandbox Code Playgroud)

但出现这个警告我想解决这个问题:

QObject::killTimer: Timers cannot be stopped from another thread
Run Code Online (Sandbox Code Playgroud)

又怎样?

更新

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

QPixmap p("myPix.png");
QGraphicsScene* scene = new QGraphicsScene();
scene->addPixmap(p);
Run Code Online (Sandbox Code Playgroud)

进入MainWindow::graphSceneSlot

Fel*_*lix 6

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

线程和 QObject

为了使您的代码正常运行,必须将图形场景从并发线程“移动”到主线程。这可以通过使用来完成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);
    ...
}
Run Code Online (Sandbox Code Playgroud)

您绝对应该阅读有关 Qt 中的线程和对象的更多内容。此链接将引导您访问文档,其中有更详细的解释:Threads and QObjects