QQmlComponent Class

QQmlComponent 类封装了一个 QML 组件定义。更多

头文件: #include <QQmlComponent>
CMake: find_package(Qt6 REQUIRED COMPONENTS Qml)
target_link_libraries(mytarget PRIVATE Qt6::Qml)
qmake: QT += qml
在 QML 中: Component
继承: QObject

公共类型

enum CompilationMode { PreferSynchronous, Asynchronous }
enum Status { Null, Ready, Loading, Error }

属性

公共职能

QQmlComponent(QQmlEngine *engine, QObject *parent = nullptr)
QQmlComponent(QQmlEngine *engine, const QString &fileName, QObject *parent = nullptr)
QQmlComponent(QQmlEngine *engine, const QUrl &url, QObject *parent = nullptr)
QQmlComponent(QQmlEngine *engine, const QString &fileName, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)
QQmlComponent(QQmlEngine *engine, const QUrl &url, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)
(since 6.5) QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QObject *parent = nullptr)
(since 6.5) QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)
virtual ~QQmlComponent() override
virtual QObject *beginCreate(QQmlContext *context)
virtual void completeCreate()
virtual QObject *create(QQmlContext *context = nullptr)
void create(QQmlIncubator &incubator, QQmlContext *context = nullptr, QQmlContext *forContext = nullptr)
QObject *createWithInitialProperties(const QVariantMap &initialProperties, QQmlContext *context = nullptr)
QQmlContext *creationContext() const
QQmlEngine *engine() const
QList<QQmlError> errors() const
(since 6.5) bool isBound() const
bool isError() const
bool isLoading() const
bool isNull() const
bool isReady() const
qreal progress() const
void setInitialProperties(QObject *object, const QVariantMap &properties)
QQmlComponent::Status status() const
QUrl url() const

公共插槽

(since 6.5) void loadFromModule(QAnyStringView uri, QAnyStringView typeName, QQmlComponent::CompilationMode mode = PreferSynchronous)
void loadUrl(const QUrl &url)
void loadUrl(const QUrl &url, QQmlComponent::CompilationMode mode)
void setData(const QByteArray &data, const QUrl &url)

信号

void progressChanged(qreal progress)
void statusChanged(QQmlComponent::Status status)

详细说明

组件是可重用的、封装的 QML 类型,具有定义明确的接口。

QQmlComponent 实例可从 QML 文件创建。例如,如果有这样一个main.qml 文件:

import QtQuick 2.0

Item {
    width: 200
    height: 200
}

下面的代码将此 QML 文件作为组件加载,使用create() 创建此组件的实例,然后查询Itemwidth 值:

QQmlEngine *engine = new QQmlEngine;
QQmlComponent component(engine, QUrl::fromLocalFile("main.qml"));

QObject *myObject = component.create();
QQuickItem *item = qobject_cast<QQuickItem*>(myObject);
int width = item->width();  // width = 200

要在没有QQmlEngine 实例的代码中创建组件实例,可以使用qmlContext() 或qmlEngine() 。例如,在下面的场景中,子项目是在QQuickItem 子类中创建的:

void MyCppItem::init()
{
    QQmlEngine *engine = qmlEngine(this);
    // Or:
    // QQmlEngine *engine = qmlContext(this)->engine();
    QQmlComponent component(engine, QUrl::fromLocalFile("MyItem.qml"));
    QQuickItem *childItem = qobject_cast<QQuickItem*>(component.create());
    childItem->setParentItem(this);
}

请注意,在QObject 子类的构造函数中调用这些函数时,将返回null ,因为该实例还没有上下文或引擎。

网络组件

如果传给 QQmlComponent 的 URL 是网络资源,或者 QML 文档引用了网络资源,QQmlComponent 就必须先获取网络数据,然后才能创建对象。在这种情况下,QQmlComponent 将有一个Loading status 。应用程序必须等到组件Ready 后,才能调用QQmlComponent::create() 。

下面的示例展示了如何从网络资源加载 QML 文件。创建 QQmlComponent 后,它会测试该组件是否正在加载。如果是,它就连接QQmlComponent::statusChanged() 信号,否则就直接调用continueLoading() 方法。请注意,如果一个网络组件已被缓存并立即就绪,则QQmlComponent::isLoading() 可能为假。

MyApplication::MyApplication() {// ...组件= newQQmlComponent(engineQUrl("http://www.example.com/main.qml"));if(component->isLoading()) { QObject::connect(component, &QQmlComponent::statusChanged, this, &MyApplication::continueLoading); }else{ continueLoading(); } }voidMyApplication::continueLoading() {if(component->isError()) {...        qWarning() << component->errors();
    }else{ QObject*myObject =  component->create(); } }

成员类型文档

enum QQmlComponent::CompilationMode

指定QQmlComponent 应立即还是异步加载组件。

常数说明
QQmlComponent::PreferSynchronous0首选立即加载/编译组件,阻塞线程。这并非总是可行;例如,远程 URL 将总是异步加载。
QQmlComponent::Asynchronous1在后台线程中加载/编译组件。

enum QQmlComponent::Status

指定QQmlComponent 的加载状态。

常量说明
QQmlComponent::Null0QQmlComponent 没有数据。调用loadUrl() 或setData() 添加 QML 内容。
QQmlComponent::Ready1QQmlComponent 已准备就绪,可调用create() 。
QQmlComponent::Loading2QQmlComponent 正在加载网络数据。
QQmlComponent::Error3发生错误。调用errors() 可获取errors 的列表。

属性文档

[read-only] progress : const qreal

加载组件的进度,从 0.0(未加载)到 1.0(已完成)。

访问功能:

qreal progress() const

通知信号:

void progressChanged(qreal progress)

[read-only] status : const Status

组件的当前status

访问功能:

QQmlComponent::Status status() const

通知信号:

void statusChanged(QQmlComponent::Status status)

[read-only] url : const QUrl

组件 URL。这是传递给构造函数、loadUrl() 或setData() 方法的 URL。

访问函数:

QUrl url() const

成员函数文档

QQmlComponent::QQmlComponent(QQmlEngine *engine, QObject *parent = nullptr)

创建一个无数据的 QQmlComponent,并为其指定engineparent 。使用setData() 设置数据。

QQmlComponent::QQmlComponent(QQmlEngine *engine, const QString &fileName, QObject *parent = nullptr)

从给定的fileName 创建一个 QQmlComponent,并为其指定parentengine

另请参见 loadUrl().

QQmlComponent::QQmlComponent(QQmlEngine *engine, const QUrl &url, QObject *parent = nullptr)

从给定的url 中创建一个 QQmlComponent,并为其指定parentengine

确保所提供的 URL 完整、正确,尤其是从本地文件系统加载文件时,请使用QUrl::fromLocalFile() 。

相对路径将根据QQmlEngine::baseUrl() 解析,除非指定,否则 () 就是当前工作目录。

另请参见 loadUrl()。

QQmlComponent::QQmlComponent(QQmlEngine *engine, const QString &fileName, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)

从给定的fileName 创建一个 QQmlComponent,并赋予其指定的parentengine 。如果modeAsynchronous ,该组件将被异步加载和编译。

另请参阅 loadUrl() 。

QQmlComponent::QQmlComponent(QQmlEngine *engine, const QUrl &url, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)

从给定的url 中创建一个 QQmlComponent,并赋予其指定的parentengine 。如果modeAsynchronous ,该组件将被异步加载和编译。

确保提供的 URL 完整、正确,特别是从本地文件系统加载文件时,请使用QUrl::fromLocalFile() 。

相对路径将根据QQmlEngine::baseUrl() 解析,除非指定,否则 () 就是当前工作目录。

另请参见 loadUrl()。

[explicit, since 6.5] QQmlComponent::QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QObject *parent = nullptr)

从给定的uritypeName 创建一个 QQmlComponent,并为其指定parentengine 。如果可能,将同步加载该组件。

这是一个重载函数。

该函数在 Qt 6.5 中引入。

另请参阅 loadFromModule().

[explicit, since 6.5] QQmlComponent::QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)

从给定的uritypeName 创建一个 QQmlComponent,并给它指定的parentengine 。如果modeAsynchronous ,组件将被异步加载和编译。

这是一个重载函数。

该函数在 Qt 6.5 中引入。

另请参阅 loadFromModule().

[override virtual noexcept] QQmlComponent::~QQmlComponent()

销毁QQmlComponent

[virtual] QObject *QQmlComponent::beginCreate(QQmlContext *context)

在指定的context 范围内从该组件创建一个对象实例。如果创建失败,则返回nullptr

注: 该方法提供了对组件实例创建的高级控制。一般来说,程序员应使用QQmlComponent::create() 来创建对象实例。

QQmlComponent 构建实例时,分为三个步骤:

  1. 创建对象层次结构,分配常量值。
  2. 首次评估属性绑定。
  3. 如果适用,在对象上调用QQmlParserStatus::componentComplete() 。

QQmlComponent::beginCreate()与QQmlComponent::create() 的不同之处在于,它只执行第 1 步。必须调用QQmlComponent::completeCreate() 才能完成第 2 和第 3 步。

当使用附加属性向实例化组件传递信息时,这个中断点有时很有用,因为它允许在属性绑定生效前配置其初始值。

返回对象实例的所有权将转移给调用者。

注意: 将绑定分为常量值和实际绑定是故意不指定的,在不同版本的 Qt 中可能会发生变化,这取决于您是否使用qmlcachegen 以及如何使用。在 beginCreate() 返回之前或之后,都不应依赖于对任何特定绑定的评估。例如,MyType.EnumValue这样的常量表达式可能在编译时被识别为常量表达式,也可能作为绑定被延迟执行。对于-(5)"a" + " 常量字符串 "这样的常量表达式也是如此。

另请参见 completeCreate() 和QQmlEngine::ObjectOwnership

[virtual] void QQmlComponent::completeCreate()

该方法提供了对组件实例创建的高级控制。一般来说,程序员应使用QQmlComponent::create() 来创建组件。

该函数完成了从QQmlComponent::beginCreate() 开始的组件创建,必须在创建后调用。

另请参见 beginCreate()。

[virtual] QObject *QQmlComponent::create(QQmlContext *context = nullptr)

在指定的context 范围内从该组件创建一个对象实例。如果创建失败,则返回nullptr

如果contextnullptr (默认值),则会在引擎的root context 中创建实例。

返回对象实例的所有权将转移给调用者。

如果从该组件创建的对象是一个可视化项目,那么它必须有一个可视化父对象,可通过调用QQuickItem::setParentItem() 设置父对象。详情请参阅 Qt Quick 中的概念 - 视觉父对象

另请参见 QQmlEngine::ObjectOwnership

void QQmlComponent::create(QQmlIncubator &incubator, QQmlContext *context = nullptr, QQmlContext *forContext = nullptr)

使用提供的incubator 从该组件创建一个对象实例。context 指定创建对象实例的上下文。

如果contextnullptr (默认情况下),则将在引擎的root context 中创建实例。

forContext 指定了创建对象所依赖的上下文。如果 是以异步方式创建的,而 是 ,则此对象也将以异步方式创建。如果 是 (默认情况下),则 将被用于此决定。forContext QQmlIncubator::IncubationMode QQmlIncubator::AsynchronousIfNested forContext nullptr context

创建的对象及其创建状态可通过incubator 查看。

另请参阅 QQmlIncubator

QObject *QQmlComponent::createWithInitialProperties(const QVariantMap &initialProperties, QQmlContext *context = nullptr)

在指定的context 内创建该组件的对象实例,并用initialProperties 初始化其顶层属性。

如果initialProperties 中的任何属性无法设置,系统将发出警告。如果有未设置的必要属性,则对象创建失败并返回nullptr ,在这种情况下,isError() 将返回true

另请参阅 QQmlComponent::create

QQmlContext *QQmlComponent::creationContext() const

返回创建组件的QQmlContext 。这只对直接从 QML 创建的组件有效。

QQmlEngine *QQmlComponent::engine() const

返回该组件的QQmlEngine

QList<QQmlError> QQmlComponent::errors() const

返回上次编译或创建操作中出现的错误列表。如果未设置isError() ,则返回空列表。

[since 6.5] bool QQmlComponent::isBound() const

如果组件是在指定pragma ComponentBehavior: Bound 的 QML 文件中创建的,则返回 true,否则返回 false。

此函数在 Qt 6.5 中引入。

bool QQmlComponent::isError() const

如果status() ==QQmlComponent::Error ,则返回 true。

bool QQmlComponent::isLoading() const

如果status() ==QQmlComponent::Loading ,则返回 true。

bool QQmlComponent::isNull() const

如果status() ==QQmlComponent::Null ,则返回 true。

bool QQmlComponent::isReady() const

如果status() ==QQmlComponent::Ready ,则返回 true。

[slot, since 6.5] void QQmlComponent::loadFromModule(QAnyStringView uri, QAnyStringView typeName, QQmlComponent::CompilationMode mode = PreferSynchronous)

在模块uri 中加载typeNameQQmlComponent 。如果类型是通过 QML 文件实现的,mode 。由 C++ 支持的类型总是同步加载的。

QQmlEngine engine;
QQmlComponent component(&engine);
component.loadFromModule("QtQuick", "Item");
// once the component is ready
std::unique_ptr<QObject> item(component.create());
Q_ASSERT(item->metaObject() == &QQuickItem::staticMetaObject);

此函数在 Qt 6.5 中引入。

另请参阅 loadUrl() 。

[slot] void QQmlComponent::loadUrl(const QUrl &url)

从提供的url 加载QQmlComponent

确保提供的 URL 完整、正确,特别是从本地文件系统加载文件时,请使用QUrl::fromLocalFile() 。

相对路径将根据QQmlEngine::baseUrl() 解析,除非指定,否则 () 就是当前工作目录。

[slot] void QQmlComponent::loadUrl(const QUrl &url, QQmlComponent::CompilationMode mode)

从提供的url 中加载QQmlComponent 。如果modeAsynchronous ,组件将被异步加载和编译。

确保提供的 URL 完整、正确,特别是从本地文件系统加载文件时,请使用QUrl::fromLocalFile() 。

相对路径将根据QQmlEngine::baseUrl() 解析,除非指定,否则 () 就是当前工作目录。

[signal] void QQmlComponent::progressChanged(qreal progress)

每当组件的加载进度发生变化时发出。progress 将是介于 0.0(未加载)和 1.0(已完成)之间的当前进度。

注: 属性progress 的通知信号。

[slot] void QQmlComponent::setData(const QByteArray &data, const QUrl &url)

设置QQmlComponent 以使用给定的 QMLdata 。如果提供url ,它将用于设置组件名称,并为该组件解析的项目提供基本路径。

警告 新组件将影响相同 URL 的任何现有组件。您不应传递现有组件的 URL。

void QQmlComponent::setInitialProperties(QObject *object, const QVariantMap &properties)

设置由QQmlComponent 创建的object 的顶级properties

该方法提供了对组件实例创建的高级控制。一般来说,程序员应使用QQmlComponent::createWithInitialProperties 从组件创建对象实例。

在调用beginCreate 之后、completeCreate 之前使用该方法。如果提供的属性不存在,则会发出警告。

该方法不允许直接设置初始嵌套属性。相反,要为具有嵌套属性的值类型属性设置初始值,可以创建该值类型,为其嵌套属性赋值,然后将该值类型作为要构造的对象的初始属性传递。

例如,为了设置 fond.bold,可以创建一个QFont ,将其权重设置为粗体,然后将字体作为初始属性传递。

[signal] void QQmlComponent::statusChanged(QQmlComponent::Status status)

每当组件状态发生变化时发出。status 将是新状态。

注: 属性status 的通知信号。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.