2

I have a QGraphicsView in my MainWindow that I created that in my Ui (of course with the base thread) and I want to set a QGraphicsScene on it from another thread.

So in constructor of MainWindow I have:

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);
...
}

and in MainWindow::generateGraph I have:

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

and in MainWindow::graphSceneSlot there is:

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

But this warning occurs which I want to solve that:

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

so how?

UPDATE

I can solve that by moving:

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

into MainWindow::graphSceneSlot

1 Answers1

6

The reason you get this warning is because the scene you created still "lives" in the concurrent thread it was created in. This means it cannot be properly "controlled" from the main thread.

Threads and QObjects

In order for your code to properly function, the graphics scene must be "moved" from the concurrent thread to the main thread. This can be done by using 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);
    ...
}

You should definitly read more about threads and objects in Qt. This link leads you to the documentation where it is explained in more detail: Threads and QObjects

Felix
  • 6,885
  • 1
  • 29
  • 54