QQuickFrameBufferObject导致PySide2崩溃

2022-02-27 00:00:00 python pyside2 qt5 qt qtquick2

问题描述

我正在尝试创建一个简单的QQuickFrameBufferObject,以便在Qt Quick中渲染一些自定义OpenGL纹理。所以我决定用PySide2来测试它。下面是一个简单的实现:

from PySide2.QtQuick import QQuickFramebufferObject
from PySide2.QtGui import QOpenGLFramebufferObjectFormat, QOpenGLFramebufferObject
from PySide2.QtCore import QSize, Qt

class FboRenderer(QQuickFramebufferObject.Renderer):
    def __init__(self, parent=None):
        super().__init__(parent)
        print("Creating renderer")

    def createFrameBufferObject(self, size):
        format = QOpenGLFramebufferObjectFormat()
        format.setAttachment(QOpenGLFramebufferObject.Depth)
        return QOpenGLFramebufferObject(size, format)

    def synchronize(self, item):
        print("Synchronizing")

    def render(self):
        print("Rendering")

class OpenGLCanvas(QQuickFramebufferObject):
    def __init__(self, parent=None):
        super().__init__(parent)

    def createRenderer(self):
        return FboRenderer()

然后要在我使用的QML中使用它:

    qmlRegisterType(OpenGLCanvas,"OpenGLCanvas", 1, 0, "OpenGLCanvas")
import QtQuick 2.12
import QtQuick.Window 2.12
import OpenGLCanvas 1.0

Window{
    id: win
    visible: true

    OpenGLCanvas{
        anchors.fill: parent
    }
}
现在应用程序运行并显示"正在创建渲染器",但几秒钟后就崩溃了。


解决方案

问题是FboRenderer()是将立即销毁的局部变量,因此它还会销毁C++对象,从而导致分段错误,因为访问了未保留的内存。

另一方面,createFrameBufferObject中有一个拼写错误,因为它必须是createFramebufferObject,这也显示了一个与初始错误类似的错误,因此解决方案也是类似的。

class FboRenderer(QQuickFramebufferObject.Renderer):
    def __init__(self):
        super().__init__()
        print("Creating renderer")
        self._fbos = []

    def createFramebufferObject(self, size):
        fmt = QOpenGLFramebufferObjectFormat()
        fmt.setAttachment(QOpenGLFramebufferObject.Depth)
        fbo = QOpenGLFramebufferObject(size, fmt)
        self._fbos.append(fbo)
        return fbo

    def synchronize(self, item):
        print("Synchronizing")

    def render(self):
        print("Rendering")


class OpenGLCanvas(QQuickFramebufferObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._renderer = None

    def createRenderer(self):
        if self._renderer is None:
            self.renderer = FboRenderer()
        return self.renderer

相关文章