From 7d44b16bc3a6eb162cb515564ea586786cea3355 Mon Sep 17 00:00:00 2001 From: rewine Date: Thu, 5 Feb 2026 14:09:17 +0800 Subject: [PATCH] refactor: replace beginCreate with createWithInitialProperties MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refactored QML component creation to use createWithInitialProperties API instead of manual beginCreate/completeCreate flow. This simplifies the code and follows Qt's recommended pattern for component creation with initial properties. Added proper error handling and null checks for context and created objects. Changed fatal errors to critical errors with appropriate cleanup to prevent crashes. 重构 QML 组件创建逻辑,使用 createWithInitialProperties API 替代手动 beginCreate/completeCreate 流程。简化代码并遵循 Qt 推荐的带初始属性组件 创建模式。添加了适当的错误处理和对上下文及创建对象的空值检查。将致命错误 改为关键错误并添加适当的清理操作以防止崩溃。 --- src/core/qmlengine.cpp | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/core/qmlengine.cpp b/src/core/qmlengine.cpp index 9cc489446..e692c536b 100644 --- a/src/core/qmlengine.cpp +++ b/src/core/qmlengine.cpp @@ -52,18 +52,29 @@ QQuickItem *QmlEngine::createComponent(QQmlComponent &component, const QVariantMap &properties) { auto context = qmlContext(parent); - auto obj = component.beginCreate(context); - if (!properties.isEmpty()) { - component.setInitialProperties(obj, properties); + if (!context) { + qCCritical(qLcQmlEngine) << "Can't get QML context from parent"; + return nullptr; } + + QObject *obj = component.createWithInitialProperties(properties, context); + + if (!obj) { + qCCritical(qLcQmlEngine) << "Component creation failed:" << component.errorString(); + return nullptr; + } + auto item = qobject_cast(obj); if (!item) { - qCFatal(qLcQmlEngine) << "Can't create component:" << component.errorString(); + qCCritical(qLcQmlEngine) << "Created object is not a QQuickItem. Actual type:" + << obj->metaObject()->className(); + delete obj; + return nullptr; } + QQmlEngine::setObjectOwnership(item, QQmlEngine::objectOwnership(parent)); item->setParent(parent); item->setParentItem(parent); - component.completeCreate(); return item; } @@ -85,12 +96,17 @@ QQuickItem *QmlEngine::createDecoration(SurfaceWrapper *surface, QQuickItem *par QObject *QmlEngine::createWindowMenu(QObject *parent) { auto context = qmlContext(parent); - auto obj = windowMenuComponent.beginCreate(context); + if (!context) { + qCCritical(qLcQmlEngine) << "Can't get QML context from parent for WindowMenu"; + return nullptr; + } + + auto obj = windowMenuComponent.create(context); if (!obj) { - qCFatal(qLcQmlEngine) << "Can't create WindowMenu:" << windowMenuComponent.errorString(); + qCCritical(qLcQmlEngine) << "Can't create WindowMenu:" << windowMenuComponent.errorString(); + return nullptr; } obj->setParent(parent); - windowMenuComponent.completeCreate(); return obj; }