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 类型。
可以从 QML 文件创建 QQmlComponent 实例。例如,如果有一个如下所示的main.qml 文件:
import QtQuick 2.0
Item {
width: 200
height: 200
}以下代码将此 QML 文件加载为组件,使用create() 创建该组件的实例,然后查询Item 的width 值:
QQmlEngine*engine = newQQmlEngine;
QQmlComponent component(engine,QUrl::fromLocalFile("main.qml"));
if(component.isError()) {
qWarning() << "Failed to load main.qml:" << component.errors();
return 1;
}
QObject*myObject =component.create();
if(component.isError()) {
qWarning() << "Failed to create instance of main.qml:" << component.errors();
return 1;
}
QQuickItem*item =qobject_cast<QQuickItem*>(myObject);
intwidth= 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() 可能返回 false。
MyApplication::MyApplication()
{
// ...
component= newQQmlComponent(engine,QUrl("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::PreferSynchronous | 0 | 优先立即加载/编译组件,并阻塞线程。但这并非总是可行;例如,远程 URL 总是会异步加载。 |
QQmlComponent::Asynchronous | 1 | 在后台线程中加载/编译组件。 |
enum QQmlComponent::Status
指定QQmlComponent 的加载状态。
| 常量 | 值 | 描述 |
|---|---|---|
QQmlComponent::Null | 0 | 该QQmlComponent 中没有数据。请调用loadUrl()或setData()来添加QML内容。 |
QQmlComponent::Ready | 1 | 此QQmlComponent 已准备就绪,可调用create()。 |
QQmlComponent::Loading | 2 | 此QQmlComponent 正在加载网络数据。 |
QQmlComponent::Error | 3 | 发生错误。请调用errors() 以获取errors 的列表。 |
属性文档
[read-only] progress : qreal
组件加载进度,从 0.0(未加载)到 1.0(完成)。
访问函数:
| qreal | progress() const |
通知器信号:
| void | progressChanged(qreal progress) |
[read-only] status : 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,并为其指定engine 和parent 。使用setData()设置数据。
QQmlComponent::QQmlComponent(QQmlEngine *engine, const QString &fileName, QObject *parent = nullptr)
根据给定的fileName 创建一个QQmlComponent,并为其指定parent 和engine 。
另请参阅 loadUrl()。
QQmlComponent::QQmlComponent(QQmlEngine *engine, const QUrl &url, QObject *parent = nullptr)
根据给定的url 创建一个QQmlComponent,并为其指定parent 和engine 。
请确保提供的 URL 完整且正确,特别是从本地文件系统加载文件时,请使用QUrl::fromLocalFile()。
相对路径将相对于QQmlEngine::baseUrl() 进行解析,除非另有指定,否则该路径即为当前工作目录。
另请参阅 loadUrl()。
QQmlComponent::QQmlComponent(QQmlEngine *engine, const QString &fileName, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)
根据给定的fileName 创建一个QQmlComponent,并为其指定parent 和engine 。如果mode 为Asynchronous ,则该组件将异步加载和编译。
另请参阅 loadUrl()。
QQmlComponent::QQmlComponent(QQmlEngine *engine, const QUrl &url, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)
根据给定的url 创建一个QQmlComponent,并为其指定parent 和engine 。如果mode 为Asynchronous ,则该组件将以异步方式加载和编译。
请确保提供的 URL 完整且正确,特别是从本地文件系统加载文件时,请使用QUrl::fromLocalFile()。
相对路径将根据QQmlEngine::baseUrl() 进行解析,除非另有指定,否则该函数默认指向当前工作目录。
另请参阅 loadUrl()。
[explicit, since 6.5] QQmlComponent::QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QObject *parent = nullptr)
根据给定的uri 和typeName 创建一个QQmlComponent,并为其指定parent 和engine 。如果可能,该组件将以同步方式加载。
这是一个重载函数。
该函数在 Qt 6.5 中引入。
另请参阅 loadFromModule()。
[explicit, since 6.5] QQmlComponent::QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)
根据给定的uri 和typeName 创建一个QQmlComponent,并为其指定parent 和engine 。如果mode 为Asynchronous ,则该组件将异步加载和编译。
这是一个重载函数。
该函数在 Qt 6.5 中引入。
另请参阅 loadFromModule()。
[override virtual noexcept] QQmlComponent::~QQmlComponent()
摧毁QQmlComponent 。
[virtual] QObject *QQmlComponent::beginCreate(QQmlContext *context)
在指定的context 内,从该组件创建一个对象实例。如果创建失败,则返回nullptr 。
注意:此 方法可对组件实例的创建进行高级控制。通常情况下,程序员应使用QQmlComponent::create()来创建对象实例。
当QQmlComponent 构建实例时,该过程分为三个步骤:
- 创建对象层次结构,并赋值给常量。
- 首次评估属性绑定。
- 如果适用,将对对象调用 `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 。
如果context 为nullptr (默认值),则将在引擎的root context 中创建该实例。
返回的对象实例的所有权将转移给调用方。
如果从该组件创建的对象是一个视觉项,则它必须有一个视觉父项,可通过调用QQuickItem::setParentItem() 来设置。更多详细信息,请参阅《Qt Quick 》中的“概念 - 视觉父项”。
另请参阅 QQmlEngine::ObjectOwnership 。
void QQmlComponent::create(QQmlIncubator &incubator, QQmlContext *context = nullptr, QQmlContext *forContext = nullptr)
使用提供的incubator 从该组件创建对象实例。context 指定了创建对象实例的上下文。
如果context 为nullptr (默认值),则将在引擎的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 。
如果context 为nullptr (默认值),则会在引擎的root context 中创建该实例。
返回的对象实例的所有权将转移给调用方。
另请参阅 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 中加载typeName 的QQmlComponent 。如果类型是通过 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() 进行解析,除非另有指定,否则该路径即为当前工作目录。
注意:此 插槽被重载。要连接到此插槽:
// Connect using qOverload:
connect(sender, &SenderClass::signal,
qmlComponent, qOverload(&QQmlComponent::loadUrl));
// Or using a lambda as wrapper:
connect(sender, &SenderClass::signal,
qmlComponent, [receiver = qmlComponent](const QUrl &url) { receiver->loadUrl(url); }); [slot] void QQmlComponent::loadUrl(const QUrl &url, QQmlComponent::CompilationMode mode)
从提供的url 加载QQmlComponent 。如果mode 的值为Asynchronous ,则该组件将异步加载并编译。
请确保提供的 URL 完整且正确,特别是从本地文件系统加载文件时,请使用QUrl::fromLocalFile()。
相对路径将根据QQmlEngine::baseUrl() 进行解析,除非另有指定,否则该路径即为当前工作目录。
注意:此 插槽已被重载。要连接到此插槽:
// Connect using qOverload:
connect(sender, &SenderClass::signal,
qmlComponent, qOverload(&QQmlComponent::loadUrl));
// Or using a lambda as wrapper:
connect(sender, &SenderClass::signal,
qmlComponent, [receiver = qmlComponent](const QUrl &url, QQmlComponent::CompilationMode mode) { receiver->loadUrl(url, mode); }); [signal] void QQmlComponent::progressChanged(qreal progress)
每当组件的加载进度发生变化时触发。progress 表示当前进度,取值范围为 0.0(尚未加载)到 1.0(已完成)。
注意: 这是属性progress的通知 信号。
[slot] void QQmlComponent::setData(const QByteArray &data, const QUrl &url)
将QQmlComponent 设置为使用给定的QML文件data 。如果提供了url ,则将其用于设置组件名称,并为该组件解析的项目提供基路径。该组件将以同步方式加载和编译。
警告:新组件将 覆盖任何具有相同 URL 的现有组件。请勿传入现有组件的 URL。
void QQmlComponent::setInitialProperties(QObject *object, const QVariantMap &properties)
设置由QQmlComponent 生成的object 的顶级properties 。
此方法提供了对组件实例创建的高级控制。通常,程序员应使用 `QQmlComponent::createWithInitialProperties ` 从组件创建对象实例。
请在调用beginCreate 之后、completeCreate 之前使用此方法。如果提供的属性不存在,则会发出警告。
此方法不允许直接设置初始嵌套属性。相反,要为具有嵌套属性的值类型属性设置初始值,可以通过创建该值类型、为其嵌套属性赋值,然后将该值类型作为要构建的对象的初始属性传递来实现。
例如,要设置 `fond.bold`,可以创建一个 `QFont`,将其 `weight` 属性设置为 `bold`,然后将该字体作为初始属性传递。
[signal] void QQmlComponent::statusChanged(QQmlComponent::Status status)
每当组件的状态发生变化时触发。status 将表示新的状态。
注意: 这是属性status的通知 信号。
© 2026 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.