Skip to content

refactor: replace beginCreate with createWithInitialProperties#734

Draft
wineee wants to merge 1 commit intolinuxdeepin:masterfrom
wineee:qml
Draft

refactor: replace beginCreate with createWithInitialProperties#734
wineee wants to merge 1 commit intolinuxdeepin:masterfrom
wineee:qml

Conversation

@wineee
Copy link
Member

@wineee wineee commented Feb 5, 2026

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 推荐的带初始属性组件 创建模式。添加了适当的错误处理和对上下文及创建对象的空值检查。将致命错误
改为关键错误并添加适当的清理操作以防止崩溃。

Summary by Sourcery

Refactor QML component and window menu creation to use Qt's create/createWithInitialProperties APIs with safer error handling and ownership management.

Bug Fixes:

  • Prevent crashes by handling null QML contexts, failed component creation, and failed QQuickItem casts with cleanup instead of fatal errors.

Enhancements:

  • Simplify QML component creation by replacing manual beginCreate/completeCreate flows with create/createWithInitialProperties.
  • Improve logging by downgrading fatal errors to critical errors while preserving error diagnostics.

@deepin-ci-robot
Copy link

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: wineee

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@sourcery-ai
Copy link

sourcery-ai bot commented Feb 5, 2026

Reviewer's Guide

Refactors QML component and menu creation to use Qt's create/createWithInitialProperties APIs instead of the manual beginCreate/completeCreate sequence, adding context/null checks, softening fatal errors to critical logs, and ensuring proper cleanup on failures.

Sequence diagram for updated QML component creation flow

sequenceDiagram
    actor Caller
    participant QmlEngine
    participant QQmlComponent
    participant QQmlContext
    participant QObject
    participant QQuickItem
    participant QtQQmlEngine

    Caller->>QmlEngine: createComponent(component, parent, properties)
    QmlEngine->>QQmlContext: qmlContext(parent)
    QQmlContext-->>QmlEngine: context
    alt context is null
        QmlEngine->>QmlEngine: log qCCritical Cant_get_QML_context_from_parent
        QmlEngine-->>Caller: nullptr
    else context is valid
        alt properties not empty
            QmlEngine->>QQmlComponent: createWithInitialProperties(properties, context)
        else properties empty
            QmlEngine->>QQmlComponent: create(context)
        end
        QQmlComponent-->>QmlEngine: obj
        alt obj is null
            QmlEngine->>QmlEngine: log qCCritical Component_creation_failed
            QmlEngine-->>Caller: nullptr
        else obj is not null
            QmlEngine->>QQuickItem: qobject_cast_QQuickItem(obj)
            QQuickItem-->>QmlEngine: item
            alt item is null
                QmlEngine->>QmlEngine: log qCCritical Cant_cast_to_QQuickItem
                QmlEngine->>QObject: delete obj
                QmlEngine-->>Caller: nullptr
            else item is valid
                QmlEngine->>QtQQmlEngine: setObjectOwnership(item, objectOwnership(parent))
                QtQQmlEngine-->>QmlEngine: void
                QmlEngine->>QQuickItem: setParent(parent)
                QmlEngine->>QQuickItem: setParentItem(parent)
                QmlEngine-->>Caller: item
            end
        end
    end
Loading

Class diagram for updated QmlEngine QML creation methods

classDiagram
    class QmlEngine {
        +QQuickItem* createComponent(QQmlComponent &component, QQuickItem *parent, const QVariantMap &properties)
        +QObject* createWindowMenu(QObject *parent)
    }

    class QQmlComponent {
        +QObject* create(QQmlContext *context)
        +QObject* createWithInitialProperties(QVariantMap properties, QmlContext *context)
        +QString errorString()
    }

    class QQmlContext {
    }

    class QQuickItem {
        +void setParent(QObject *parent)
        +void setParentItem(QQuickItem *parent)
    }

    class QObject {
        +void setParent(QObject *parent)
    }

    class QtQQmlEngine {
        +static void setObjectOwnership(QObject *object, int ownership)
        +static int objectOwnership(QObject *object)
    }

    QmlEngine --> QQmlComponent : uses
    QmlEngine --> QQuickItem : creates
    QmlEngine --> QObject : creates
    QmlEngine --> QQmlContext : uses
    QmlEngine --> QtQQmlEngine : calls_static
    QQuickItem --|> QObject
    QtQQmlEngine ..> QObject : manages_ownership
    QQmlComponent ..> QQmlContext : created_with_context
Loading

File-Level Changes

Change Details Files
Refactor generic QML component creation to use create/createWithInitialProperties with robust error handling and cleanup.
  • Replace beginCreate/completeCreate flow with createWithInitialProperties when initial properties are provided, otherwise use create
  • Add explicit null-check and critical log when qmlContext(parent) cannot be obtained and bail out early
  • Add null-check for the created QObject and log a critical error including component.errorString on failure
  • Change hard qCFatal when cast to QQuickItem fails into qCCritical, delete the created object, and return nullptr
  • Keep ownership and parenting logic intact for successfully created QQuickItem instances
src/core/qmlengine.cpp
Update window menu creation to the create API and downgrade fatal errors to recoverable critical errors.
  • Replace beginCreate/completeCreate with a single create call on windowMenuComponent
  • Add null-check and critical log when qmlContext(parent) for the WindowMenu cannot be obtained
  • Change qCFatal on WindowMenu creation failure to qCCritical and return nullptr instead of crashing
  • Preserve QObject parenting to the provided parent on successful creation
src/core/qmlengine.cpp

Possibly linked issues

  • #[Bug]: qml内存异常引起崩溃: PR changes QML component creation and adds checks/cleanup, likely addressing the intermittent QML memory-related crashes in the issue.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `src/core/qmlengine.cpp:74-57` </location>
<code_context>
     auto item = qobject_cast<QQuickItem *>(obj);
     if (!item) {
-        qCFatal(qLcQmlEngine) << "Can't create component:" << component.errorString();
+        qCCritical(qLcQmlEngine) << "Can't cast to QQuickItem:" << component.errorString();
+        delete obj;
+        return nullptr;
     }
+
</code_context>

<issue_to_address>
**issue (bug_risk):** Downgrading from `qCFatal` to `qCCritical` changes failure mode from aborting to continuing after a serious construction error.

Previously, a failed cast here would abort the process; now we just log, delete `obj`, and return `nullptr`. If callers still assume a non-null `QQuickItem*`, this can turn into a later null dereference or subtle misbehavior. Either keep this fatal, or audit/update all call sites to handle a `nullptr` return explicitly.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

auto obj = component.beginCreate(context);
if (!context) {
qCCritical(qLcQmlEngine) << "Can't get QML context from parent";
return nullptr;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Downgrading from qCFatal to qCCritical changes failure mode from aborting to continuing after a serious construction error.

Previously, a failed cast here would abort the process; now we just log, delete obj, and return nullptr. If callers still assume a non-null QQuickItem*, this can turn into a later null dereference or subtle misbehavior. Either keep this fatal, or audit/update all call sites to handle a nullptr return explicitly.

@wineee wineee mentioned this pull request Feb 5, 2026
@wineee
Copy link
Member Author

wineee commented Feb 5, 2026

可能修复:#358 的 64

至少逻辑上是优化

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors QML component creation in src/core/qmlengine.cpp to use Qt's recommended createWithInitialProperties/create APIs instead of the manual beginCreate/setInitialProperties/completeCreate flow. The changes improve error handling by adding null checks for contexts and created objects, and replace fatal errors with critical errors plus appropriate cleanup to prevent crashes.

Changes:

  • Replaced beginCreate/completeCreate pattern with createWithInitialProperties/create APIs in createComponent and createWindowMenu functions
  • Added null checks for QML contexts before component creation
  • Changed qCFatal to qCCritical with proper object cleanup (delete) to prevent memory leaks when errors occur

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 推荐的带初始属性组件
创建模式。添加了适当的错误处理和对上下文及创建对象的空值检查。将致命错误
改为关键错误并添加适当的清理操作以防止崩溃。
QQmlEngine::setObjectOwnership(item, QQmlEngine::objectOwnership(parent));
item->setParent(parent);
item->setParentItem(parent);
component.completeCreate();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

之前之所以用 being/complete 的分体式方式实现,就是为了在初始化好它的parent对象后再标记为创建完成。

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

要么改为使用 QQmlComponentPrivate::createWithProperties

@wineee wineee marked this pull request as draft February 5, 2026 09:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants