QQmlComponent 類

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)
(從 6.5 起) QQmlComponent (QQmlEngine * engine , QAnyStringView uri , QAnyStringView typeName , QObject * parent = nullptr)
(從 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
(從 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

公共槽

(從 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 )

詳細描述

Component 是可重用,具有良好定義接口的 QML 封裝類型。

A QQmlComponent instance can be created from a QML file. For example, if there is a main.qml 文件像這樣:

import QtQuick 2.0
Item {
    width: 200
    height: 200
}
					

The following code loads this QML file as a component, creates an instance of this component using create (), and then queries the Item 's width 值:

QQmlEngine *engine = new QQmlEngine;
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);
int width = item->width();  // width = 200
					

To create instances of a component in code where a QQmlEngine instance is not available, you can use qmlContext () 或 qmlEngine (). For example, in the scenario below, child items are being created within a QQuickItem subclass:

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);
}
					

Note that these functions will return null when called inside the constructor of a QObject subclass, as the instance will not yet have a context nor engine.

網絡組件

If the URL passed to QQmlComponent is a network resource, or if the QML document references a network resource, the QQmlComponent has to fetch the network data before it is able to create objects. In this case, the QQmlComponent will have a Loading status . An application will have to wait until the component is Ready before calling QQmlComponent::create ().

The following example shows how to load a QML file from a network resource. After creating the QQmlComponent, it tests whether the component is loading. If it is, it connects to the QQmlComponent::statusChanged () signal and otherwise calls the continueLoading() method directly. Note that QQmlComponent::isLoading () may be false for a network component if the component has been cached and is ready immediately.

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

成員類型文檔編製

enum QQmlComponent:: CompilationMode

Specifies whether the QQmlComponent should load the component immediately, or asynchonously.

常量 描述
QQmlComponent::PreferSynchronous 0 Prefer loading/compiling the component immediately, blocking the thread. This is not always possible; for example, remote URLs will always load asynchronously.
QQmlComponent::Asynchronous 1 Load/compile the component in a background thread.

enum QQmlComponent:: Status

指定正加載狀態為 QQmlComponent .

常量 描述
QQmlComponent::Null 0 This QQmlComponent has no data. Call loadUrl () 或 setData () to add QML content.
QQmlComponent::Ready 1 This QQmlComponent is ready and create () may be called.
QQmlComponent::Loading 2 This QQmlComponent 正加載網絡數據。
QQmlComponent::Error 3 An error has occurred. Call errors () to retrieve a list of errors .

特性文檔編製

[read-only] progress : const qreal

The progress of loading the component, from 0.0 (nothing loaded) to 1.0 (finished).

訪問函數:

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

The component URL. This is the URL passed to either the constructor, or the loadUrl (),或 setData () 方法。

訪問函數:

QUrl url () const

成員函數文檔編製

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

Create a QQmlComponent with no data and give it the specified engine and parent . Set the data with setData ().

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

Create a QQmlComponent from the given fileName and give it the specified parent and engine .

另請參閱 loadUrl ().

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

Create a QQmlComponent from the given url and give it the specified parent and engine .

Ensure that the URL provided is full and correct, in particular, use QUrl::fromLocalFile () when loading a file from the local filesystem.

Relative paths will be resolved against QQmlEngine::baseUrl (), which is the current working directory unless specified.

另請參閱 loadUrl ().

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

Create a QQmlComponent from the given fileName and give it the specified parent and engine 。若 mode is 異步 , the component will be loaded and compiled asynchronously.

另請參閱 loadUrl ().

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

Create a QQmlComponent from the given url and give it the specified parent and engine 。若 mode is 異步 , the component will be loaded and compiled asynchronously.

Ensure that the URL provided is full and correct, in particular, use QUrl::fromLocalFile () when loading a file from the local filesystem.

Relative paths will be resolved against QQmlEngine::baseUrl (), which is the current working directory unless specified.

另請參閱 loadUrl ().

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

Create a QQmlComponent from the given uri and typeName and give it the specified parent and engine . If possible, the component will be loaded synchronously.

這是重載函數。

該函數在 Qt 6.5 引入。

另請參閱 loadFromModule ().

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

Create a QQmlComponent from the given uri and typeName and give it the specified parent and engine 。若 mode is 異步 , the component will be loaded and compiled asynchronously.

這是重載函數。

該函數在 Qt 6.5 引入。

另請參閱 loadFromModule ().

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

Destruct the QQmlComponent .

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

Create an object instance from this component, within the specified context 。返迴 nullptr if creation failed.

注意: This method provides advanced control over component instance creation. In general, programmers should use QQmlComponent::create () to create object instances.

QQmlComponent constructs an instance, it occurs in three steps:

  1. The object hierarchy is created, and constant values are assigned.
  2. If applicable, QQmlParserStatus::componentComplete () is called on objects.

QQmlComponent::beginCreate() differs from QQmlComponent::create () in that it only performs step 1. QQmlComponent::completeCreate () must be called to complete steps 2 and 3.

This breaking point is sometimes useful when using attached properties to communicate information to an instantiated component, as it allows their initial values to be configured before property bindings take effect.

The ownership of the returned object instance is transferred to the caller.

注意: The categorization of bindings into constant values and actual bindings is intentionally unspecified and may change between versions of Qt and depending on whether and how you are using qmlcachegen . You should not rely on any particular binding to be evaluated either before or after beginCreate() returns. For example a constant expression like MyType.EnumValue may be recognized as such at compile time or deferred to be executed as binding. The same holds for constant expressions like -(5) or "a" + " constant string" .

另請參閱 completeCreate () 和 QQmlEngine::ObjectOwnership .

[virtual] void QQmlComponent:: completeCreate ()

This method provides advanced control over component instance creation. In general, programmers should use QQmlComponent::create () to create a component.

This function completes the component creation begun with QQmlComponent::beginCreate () and must be called afterwards.

另請參閱 beginCreate ().

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

Create an object instance from this component, within the specified context 。返迴 nullptr if creation failed.

context is nullptr (the default), it will create the instance in the 根上下文 of the engine.

The ownership of the returned object instance is transferred to the caller.

If the object being created from this component is a visual item, it must have a visual parent, which can be set by calling QQuickItem::setParentItem ()。見 概念 - Qt Quick 中的視覺父級 瞭解更多細節。

另請參閱 QQmlEngine::ObjectOwnership .

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

Create an object instance from this component using the provided incubator . context specifies the context within which to create the object instance.

context is nullptr (the default), it will create the instance in the 根上下文 of the engine.

forContext specifies a context that this object creation depends upon. If the forContext is being created asynchronously, and the QQmlIncubator::IncubationMode is QQmlIncubator::AsynchronousIfNested , this object will also be created asynchronously. If forContext is nullptr (by default), the context will be used for this decision.

The created object and its creation status are available via the incubator .

另請參閱 QQmlIncubator .

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

Create an object instance of this component, within the specified context , and initialize its top-level properties with initialProperties .

If any of the initialProperties cannot be set, a warning is issued. If there are unset required properties, the object creation fails and returns nullptr ,在這種情況下 isError () 會返迴 true .

context is nullptr (the default), it will create the instance in the 根上下文 of the engine.

The ownership of the returned object instance is transferred to the caller.

另請參閱 QQmlComponent::create .

QQmlContext *QQmlComponent:: creationContext () const

返迴 QQmlContext the component was created in. This is only valid for components created directly from QML.

QQmlEngine *QQmlComponent:: engine () const

返迴 QQmlEngine of this component.

QList < QQmlError > QQmlComponent:: errors () const

Returns the list of errors that occurred during the last compile or create operation. An empty list is returned if isError () is not set.

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

Returns true if the component was created in a QML files that specifies pragma ComponentBehavior: Bound ,否則返迴 false。

該函數在 Qt 6.5 引入。

bool QQmlComponent:: isError () const

返迴 true 若 status () == QQmlComponent::Error .

bool QQmlComponent:: isLoading () const

返迴 true 若 status () == QQmlComponent::Loading .

bool QQmlComponent:: isNull () const

返迴 true 若 status () == QQmlComponent::Null .

bool QQmlComponent:: isReady () const

返迴 true 若 status () == QQmlComponent::Ready .

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

加載 QQmlComponent for typeName in the module uri . If the type is implemented via a QML file, mode is used to load it. Types backed by C++ are always loaded synchronously.

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 )

加載 QQmlComponent from the provided url .

Ensure that the URL provided is full and correct, in particular, use QUrl::fromLocalFile () when loading a file from the local filesystem.

Relative paths will be resolved against QQmlEngine::baseUrl (), which is the current working directory unless specified.

注意: 此槽被重載。要連接到此槽:

// Connect using qOverload:
connect(qmlComponent, qOverload(&QQmlComponent::loadUrl),
        receiver, &ReceiverClass::slot);
// Or using a lambda:
connect(qmlComponent, qOverload(&QQmlComponent::loadUrl),
        this, [](const QUrl &url) { /* handle loadUrl */ });
			

更多範例和方式,見 連接到重載槽 .

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

加載 QQmlComponent from the provided url 。若 mode is 異步 , the component will be loaded and compiled asynchronously.

Ensure that the URL provided is full and correct, in particular, use QUrl::fromLocalFile () when loading a file from the local filesystem.

Relative paths will be resolved against QQmlEngine::baseUrl (), which is the current working directory unless specified.

注意: 此槽被重載。要連接到此槽:

// Connect using qOverload:
connect(qmlComponent, qOverload(&QQmlComponent::loadUrl),
        receiver, &ReceiverClass::slot);
// Or using a lambda:
connect(qmlComponent, qOverload(&QQmlComponent::loadUrl),
        this, [](const QUrl &url, QQmlComponent::CompilationMode mode) { /* handle loadUrl */ });
			

更多範例和方式,見 連接到重載槽 .

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

Emitted whenever the component's loading progress changes. progress will be the current progress between 0.0 (nothing loaded) and 1.0 (finished).

注意: 通知程序信號對於特性 progress .

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

設置 QQmlComponent to use the given QML data 。若 url is provided, it is used to set the component name and to provide a base path for items resolved by this component.

警告: The new component will shadow any existing component of the same URL. You should not pass a URL of an existing component.

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

Set top-level propertiesobject that was created from a QQmlComponent .

This method provides advanced control over component instance creation. In general, programmers should use QQmlComponent::createWithInitialProperties to create an object instance from a component.

Use this method after beginCreate and before completeCreate has been called. If a provided property does not exist, a warning is issued.

This method does not allow setting initial nested properties directly. Instead, setting an initial value for value type properties with nested properties can be achieved by creating that value type, assigning its nested property and then passing the value type as an initial property of the object to be constructed.

For example, in order to set fond.bold, you can create a QFont , set its weight to bold and then pass the font as an initial property.

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

Emitted whenever the component's status changes. status will be the new status.

注意: 通知程序信號對於特性 status .

內容

  1. 公共類型

  2. 特性

  3. 公共函數

  4. 公共槽

  5. 信號

  6. 詳細描述

  7. 網絡組件