[英]Add QQuickView element to existing window
每次使用 QTQuick 在 C++ 中單擊按鈕時,我都試圖向窗口添加一個元素。
我有一個 C++ 類:
自定義類.cpp
void CustomClass::clicked() {
QQuickView view;
view.setResizeMode(QQuickView::SizeRootObjectToView);
view.setSource(QUrl("qrc:///box.qml"));
QObject *rectangleContainer = (QObject*)findItemByName(DownloadManager::rootObjects, "rectangle");
// view.setParent(rectangleContainer); Does not work ?
view.setProperty("visible", "true");
view.show();
}
和兩個 qml 文件:
主文件
import com.acidic.customclass 1.0
ApplicationWindow {
visible: true
width: 1280
height: 800
CustomClass {
id: demo
}
Rectangle {
id: rectangle
objectName: "rectangle"
width: 200
height: 200
color: "#ffffff"
}
Button {
id: button
text: qsTr("Button")
onClicked: {s
demo.clicked();
}
}
}
盒子.qml
Item {
Text {
id: text1
text: qsTr("Box!")
font.pixelSize: 12
}
}
代碼已被縮短,但仍應足以顯示我當前的狀態。
CustomClass::clicked
按鈕被點擊時,確實叫,但我的目標是創建一個實例box.qml
並插入它作為一個孩子的rectangle
內的元素main.qml
。
不需要 c++ 后端,這可以在 qml 中使用 javascript 直接實現。
您可以在 Javascript 中使用Qt.createComponent()
添加動態對象。
創建並添加一個 javascript 資源( componentCreation.js
),此腳本首先使用Qt.createComponent()
從box.qml
創建組件,然后使用createObject()
將該新組件作為子項附加到"rectangle"
元素:
componentCreation.js
代碼:
var component;
var box;
function createBoxObject() {
component = Qt.createComponent("box.qml");
box = component.createObject(rectangle, {"x": 100, "y": 100});
}
就是這樣,在 main.qml 中導入 javascript,同時調用onClicked
按鈕中的腳本:
import com.acidic.customclass 1.0
import "componentCreation.js" as MyScript
ApplicationWindow {
visible: true
width: 1280
height: 800
CustomClass {
id: demo
}
Rectangle {
id: rectangle
objectName: "rectangle"
width: 200
height: 200
color: "#ffffff"
}
Button {
id: button
text: qsTr("Button")
onClicked: {
MyScript.createBoxObject();
}
}
}
注意:我將 box.qml 添加到資源中以便直接訪問。 創建的對象將成為 main 中矩形對象的子對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.