我一直在努力解决我的问题,但到目前为止我还没有找到解决方案
我有一个 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/