我正在尝试创建一个简单的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