向基于QWidget的UI添加3D视图

2024-10-01 05:02:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试向现有的QMainWindow添加一个带有菜单、状态栏等的三维视图。我知道有两种方法可以实现这一点:

选项1

选项1不工作,我有下面的代码

class View3D(QWidget):
    def __init__(self):
        self.view = Qt3DWindow()
        self.createWindowContainer(self.view);

        # put some nodes in the scene
        scene = createScene()
        # Camera
        camera = self.view.camera()
        camera.lens().setPerspectiveProjection(45.0, 16.0 / 9.0, 0.1, 1000.0)
        camera.setPosition(QVector3D(0.0, 0.0, 40.0))
        camera.setViewCenter(QVector3D(0.0, 0.0, 0.0))

        # For camera controls.
        camController = QFirstPersonCameraController(scene)
        camController.setLinearSpeed(50.0)
        camController.setLookSpeed(180.0)
        camController.setCamera(camera)

        # assign root node to the view
        view.setRootEntity(scene)

然后,这个View3D小部件被添加到QMainWindow的布局中。由于某种原因,这一点失败了:“运行时错误:已包装的Qt3DWindows类型的C/C++对象已被删除”。在

我的猜测是PyQt只跟踪一个主窗口,当Qt3DWindow被创建时,QMainWindow被释放,程序崩溃。在

而且,这种方法感觉有点像黑客,在窗口中添加一个窗口。我觉得这不是一个好办法。在

方案2

选项2适用于我,只是现在我不能访问高级函数,比如Qt3DWindow.camera()或{}。在

相反,所有的在线教程都显示可以使用QGLWidget绘制三角形,但没有一个更进一步,使用/重新实现高级界面和场景图。在

据我所知,这在源代码中的PyQt5官方示例中也没有体现出来。basicshapes-py.py示例与我要实现的最接近,但是它似乎在Qt3DWindow中添加了几个按钮,这对我不好,因为我需要QMainWindow作为基类。在

因此,将3D视图集成到基于QWidget的UI中的推荐方法是什么?

选项(1)

@G.M.注释后的新代码

^{pr2}$

我在控制台中收到以下错误:

QOpenGLContext::swapBuffers() called with non-exposed window, behavior is undefined
Qt3D.Renderer.Backend: bool __cdecl Qt3DRender::Render::GraphicsContext::makeCurrent(class QSurface *) makeCurrent failed
Qt3D.Renderer.Backend: bool __cdecl Qt3DRender::Render::GraphicsContext::makeCurrent(class QSurface *) makeCurrent failed

Tags: 方法selfview视图选项scene容器class