它似乎應該有一個解決方案。假設我有一個包含以下內容的 Test.qml 檔案:
import QtQuick 2.0
Rectangle {
color: "green"
Row {
id: row
spacing: 10
anchors.fill: parent
Rectangle {
color: "red";
width: 100;
height: 100;
}
Rectangle {
color: "red";
width: 100;
height: 100;
}
Rectangle {
color: "red";
width: 100;
height: 100;
}
}
}
現在假設我們想在另一個檔案(如 main.qml)中使用這個 Test.qml:
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
id: window
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Test {
anchors.fill: parent;
// I want to be able to add new items (rects) to the row inside Test.qml
}
}
現在假設我們想將專案擴展到 Test.qml 中的行物件,但我們想從 main.qml 添加。我們怎么能做到這一點?這甚至可能嗎?
(僅供參考:此功能的應用是開發一個占位符表單并填寫其他專案中的專案,這樣我們就可以跳過重復的代碼。)
uj5u.com熱心網友回復:
您可以動態創建物件:
MyRow.qml:
Row {
id: row
spacing: 10
anchors.fill: parent
Rectangle {
color: "red";
width: 100;
height: 100;
}
}
main.qml:
MyRow{
id: myRow
Component.onCompleted: Qt.createQmlObject('import QtQuick 2.0; Rectangle {color: "green"; width: 100; height: 100}', myRow)
}
uj5u.com熱心網友回復:
您可以在不動態創建物件的情況下執行此操作。您需要使用別名為您的行內容的默認屬性。默認屬性意味著添加到您的物件的專案實際上將分配給該屬性。在 Test.qml 中,添加:
Rectangle {
color: "green"
default property alias contents: row.data
Row {
id: row
...
}
}
現在您可以從 main.qml 向其中添加其他專案,如下所示:
Test {
anchors.fill: parent;
// Automatically gets added to 'row'
Rectangle {
color: "blue"
width: 100
height: 100
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/417489.html
標籤:
