c++ - 从另一个线程渲染到 QWindow

标签 c++ multithreading qt opengl

我一直在努力解决我的问题,但到目前为止我还没有找到解决方案

我有一个 QT 应用程序,现在我需要在其中添加一个 QWindow 以使用 opengl 进行绘图。

我知道我需要调用 QWidget::createWindowContainer() 来创建 QWidget,我可以将其插入到另一个小部件或主窗口中。 现在,我已经在我拥有的子类 QWindow 类中创建了一个上下文。当窗口暴露时,我会这样做。然后我在我的渲染类所在的位置创建了另一个线程,将 QOpenGLContext 传递给它,使其成为当前线程,但无论我尝试什么,它都不起作用。

QWindow 的子类我只是初始化上下文,仅此而已(我在构造函数中设置了表面类型):

void OpenGLWindow::initialize()
{
    if (!m_context) {
        m_context = new QOpenGLContext();
        m_context->setFormat(requestedFormat());
        m_context->create();
    }

    if(!isRunning) {
    thread = new ThreadHelper(m_context, this);
    thread->start();
    }
} 

然后是线程助手:

ThreadHelper::ThreadHelper(QOpenGLContext *context, OpenGLWindow *window) : 
m_window(window),
m_context(context)
{
}


void ThreadHelper::run()
{
    m_context->makeCurrent(m_window);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    glClearColor(1.0, 0.0, 0.0, 0.5);

    // the rendering is done here, it's a loop, where I loop 
    // over classes and call the render method
}

void ThreadHelper::swapOpenGLBuffers(){
    m_context->swapBuffers(m_window);
}

它在 m_context->makeCurrent(m_window) 行崩溃。

还尝试将上下文移动到另一个线程但没有成功,我收到一个运行时错误,提示它无法移动。

最佳答案

来自文档:

QOpenGLContext can be moved to a different thread with moveToThread(). Do not call makeCurrent() from a different thread than the one to which the QOpenGLContext object belongs. A context can only be current in one thread and against one surface at a time, and a thread only has one context current at a time.

因此您需要在启动线程之前调用类似m_context->moveToThread(thread) 的方法。这可能对你不起作用,因为你试图在另一个线程中调用它。 moveToThread 必须在当前拥有该对象的线程(即创建它的线程)中调用。

关于c++ - 从另一个线程渲染到 QWindow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22568527/

相关文章:

java - 访问派生类对象的字段,C++ vs Java

c++ - 近似 e^1 :( 的错误逻辑

multithreading - CopyOnWriteArrayList不能按预期工作

Python 主线程中断

java - 为什么在 jUnit 测试中非守护线程会终止?

c++ - QComboBox 和 HeaderItem

c++ - lvlc-qt 缺少编译错误

c++ - 从不同的 C++ 类访问 Mysql * 连接变量

qt - 为什么 QTWebKit 远远落后于 Google Chrome (Chromium)

c++ - Qt:如何获取正在运行的 QProcess 的实时输出