QML中Pane内嵌Scene3D时3D场景无法正常显示频繁闪烁问题求解
问题原因
你遇到的Scene3D闪烁问题完全由代码中的可复现错误导致,直接对应控制台输出的报错信息:
- 布局用法冲突:
Scene3D是ColumnLayout的直接子元素,Qt Quick Layout会全权管理子元素的尺寸位置,此时给Scene3D设置anchors.fill: parent属于未定义行为,会触发组件尺寸反复重算,导致Scene3D依赖的OpenGL帧缓冲反复重建失败,最终出现闪烁。 - 未定义变量错误:
SwipeView的currentIndex绑定了不存在的tabBar变量,会导致父组件状态异常不停重排,进一步加剧渲染上下文冲突。 - 窗口尺寸策略未配置:
QQuickView没有开启SizeRootObjectToView,根组件和窗口尺寸不匹配也会放大布局冲突的影响。
删除外层Pane后闪烁消失,是因为Pane默认自带的内边距会加剧布局尺寸计算冲突,去掉后冲突被临时弱化,但底层错误仍然存在。
修复步骤
- 修改C++主函数,放开注释的窗口配置代码:
#include <QGuiApplication> #include <QQuickView> int main(int argc, char **argv) { QGuiApplication app(argc, argv); QQuickView view; view.resize(500, 500); view.setResizeMode(QQuickView::SizeRootObjectToView); view.setSource(QUrl("qrc:/main.qml")); view.show(); return app.exec(); }
- 修改QML代码,修复布局和未定义变量问题:
- 删除
SwipeView中不存在的tabBar绑定(如果需要Tab栏可自行补充TabBar组件后再恢复绑定) - 替换
Scene3D的anchors属性为Layout专用属性
import QtQuick.Scene3D 2.0 import Qt3D.Core 2.0 import Qt3D.Render 2.9 import Qt3D.Input 2.0 import Qt3D.Extras 2.9 import QtQuick 2.0 import QtQuick 2.13 as QQ2 import QtQuick.Layouts 1.13 import QtQuick.Controls 2.13 Pane{ SwipeView{ anchors.fill: parent id: swipeView // 移除不存在的tabBar绑定,需要Tab栏可自行补充后再恢复 // currentIndex: tabBar.currentIndex ColumnLayout{ Text { text: "Click me000!" MouseArea { anchors.fill: parent } } } ColumnLayout{ Text { text: "Click me333!" MouseArea { anchors.fill: parent } } } ColumnLayout { Scene3D { id: scene3d // 替换anchors为Layout属性 Layout.fillWidth: true Layout.fillHeight: true Layout.margins: 10 focus: true aspects: ["input", "logic"] cameraAspectRatioMode: Scene3D.AutomaticAspectRatio Entity { id: sceneRoot Camera { id: camera projectionType: CameraLens.PerspectiveProjection fieldOfView: 45 aspectRatio: 16/9 nearPlane : 0.1 farPlane : 1000.0 position: Qt.vector3d( -15, -15, -15 ) upVector: Qt.vector3d( 0.0, 1.0, 0.0 ) viewCenter: Qt.vector3d( 0.0, 0.0, 0.0 ) } OrbitCameraController { camera: camera } components: [ RenderSettings { activeFrameGraph: ForwardRenderer { clearColor: Qt.rgba(0, 0.5, 1, 1) camera: camera } }, InputSettings { } ] PhongAlphaMaterial { id: material alpha: 1 ambient: Qt.rgba( 0, .5, .5, 1.0 ) diffuse: Qt.rgba( 0, .5, .5, 1.0 ) shininess: 50 } Transform { id: torusTransform1 translation: Qt.vector3d(-10,-10,-10) } Transform { id: torusTransform2 translation: Qt.vector3d(-10, -10, -8) } CylinderMesh { id: cyMesh1 length: 5 radius: 1 rings: 20 slices: 20 } CylinderMesh { id: cyMesh2 length: 5 radius: 1 rings: 20 slices: 20 } Entity { id: cyEntity1 components: [ cyMesh1, material, torusTransform1 ] } Entity { id: cyEntity2 components: [ cyMesh2, material, torusTransform2 ] } QQ2.NumberAnimation { target: cyMesh1 property: "length" duration: 10000 from: 5 to: 0 loops: QQ2.Animation.Infinite running: true } } } } } }
修复后所有控制台报错会消失,Scene3D可正常渲染无闪烁。
内容的提问来源于stack exchange,提问作者kenash0625
相关产品推荐
相关产品推荐

