有没有办法从C++创建/附加QML组件?
例如,如果我有这个 QML:
Window {
id: window
objectName: "windowName"
title: "windowName"
width: 480
height: 800
Rectangle {
id: frmHeader
objectName: "frmHeader"
width: parent.width
height: parent.height
}
}
是否可以在矩形上附加TextInput
?
在您的情况下,您应该按照以下步骤操作:
-
通过 findChild 使用 objectName 查找项目。
-
使用 QQml组件创建项目
-
将父项添加为属性。
主.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlComponent>
#include <QQmlProperty>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
QObject *frmHeader = engine.rootObjects().first()->findChild<QObject *>("frmHeader");
QQmlComponent component(&engine);
component.setData("import QtQuick 2.7 n"
"TextInput{ n"
"text: "hello world :D" n"
"}", QUrl());
QObject *text_object = component.create();
if(text_object && frmHeader)
Q_ASSERT(QQmlProperty::write(text_object,
"parent",
QVariant::fromValue(frmHeader)));
return app.exec();
}