QQmlComponent类封装了QML组件定义。
组件是具有良好定义的接口的可重用的,封装的QML类型。
可以从QML文件创建QQmlComponent实例。例如,如果有一个main.qml文件,如下所示:
import QtQuick 2.0
Item {
width: 200
height: 200
}
以下代码将此QML文件作为组件加载,使用create()创建此组件的实例,然后查询Item的width值:
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 =