从线程更新场景? [英] Update Scene from Thread?

查看:118
本文介绍了从线程更新场景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用线程中的QGraphicsScene更新QGraphicsView.

I need to update a QGraphicsView with a QGraphicsScene from a thread.

下面是一些伪代码示例,说明我正在做的事情导致我出现问题(运行时错误).

Below is some pseudo'ish code example of what I am doing which is causing me issues (runtime errors).

我在做什么错,我应该怎么做?

What am I doing wrong, and how should I be doing it?

主应用程序:

void Main::startThread()
{
  view = new QGraphicsView(...);
  thread = new MyThread(...);
  connect(thread, SIGNAL(doSceneUpdate(QGraphicsScene*)), this, SLOT(updateScene(QGraphicsScene*)));
  thread->start();
}

void Main::updateScene(QGraphicsScene *scene)
{
  view->SetScene(scene);
  view->show();
  repaint();
}

线程:

void MyThread::run()
{
  QGraphicsScene *scene = new QGraphicsScene(...);
  while(1)
  {
    //draw stuff on the scene
    emit doSceneUpdate(scene);
    //some delay
  }

提前谢谢!

错误是:

ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread
3e53c0. Receiver '' (of type 'QGraphicsScene') was created in thread 1476cd18", file c:\Qt\qt-everywhere-opensource-src-4.8.2\src\corelib\kernel\qcoreapplication.cpp, line 501

推荐答案

我在做什么错,我应该怎么做?

What am I doing wrong, and how should I be doing it?

我认为规范的答案是此处-简而言之,该文章指出您不应该将QThread子类化,而应该使用裸"(即未子类化)QThread对象,并将其started()信号连接到插槽线程启动后,它将在该线程的上下文中运行.这样,对象线程所有权问题将自动为您处理.

I think the canonical answer is here -- in a nutshell, the article states that you shouldn't be subclassing QThread, but rather you should use a "bare" (i.e. not-subclassed) QThread object and connect its started() signal to a slot that will then be run in the context of that thread, after the thread starts. That way the object-thread-ownership issues are handled automatically for you.

还请注意,通常不允许除Qt主线程以外的其他线程创建或直接与QGraphicsScene之类的GUI对象进行交互,因为这样做会引入竞争条件,因为操作会同时在Qt的GUI事件循环中在幕后进行. .如果要使用单独的线程,则需要使其远离GUI对象,而只是使其发出异步信号和/或将事件发送到main/GUI线程以使main/GUI线程执行GUI对象代表它进行更新.

Note also that threads other than the main Qt thread are generally not allowed to create or interact directly with GUI objects like QGraphicsScene, since doing that would introduce race conditions due to the operations going on simultaneously behind the scenes in Qt's GUI event loop. If you want to use a separate thread, you'll need to keep it away from your GUI objects, and instead just have it emit asynchronous signals and/or send Events to the main/GUI thread to get the main/GUI thread to do the GUI-object updates on its behalf.

这篇关于从线程更新场景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆