[英]Is it possible to create a Qml Component from C++?
有什么方法可以從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
}
}
是否可以在Rectangle上追加TextInput
?
在您的情況下,您應該執行以下步驟:
通過findChild使用objectName查找項目。
用QQmlComponent創建項目
將父項添加為屬性。
main.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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.