[英]Add elements dynamically to SplitView in QML
我正在使用QML,我想動態地向SplitView添加元素,例如。 onMouseClick,但到目前為止我沒有找到答案。
到目前為止我發現的是, SplitView
的默認屬性設置為它的第一個子data
屬性。 所以我想我應該嘗試添加新動態創建的組件,並將父組設置為該子組( splitView1.children[0]
)。 不幸的是,這也不起作用。 在組件加載完成后,第一個子節點的子節點數為零(看起來像SplitLayout的Component.onCompleted事件調用一個將這些子節點移動到其他地方的函數)。 因此,添加的子項不會呈現(並且不響應任何布局附加屬性)。
請參閱以下代碼段:
import QtQuick 2.1
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.0
ApplicationWindow {
width: 600
height: 400
SplitView {
anchors.fill: parent
Rectangle {
id: column
width: 200
Layout.minimumWidth: 100
Layout.maximumWidth: 300
color: "lightsteelblue"
}
SplitView {
id: splitView1
orientation: Qt.Vertical
Layout.fillWidth: true
Rectangle {
id: row1
height: 200
color: "lightblue"
Layout.minimumHeight: 1
}
// Rectangle { //I want to add Rectangle to splitView1 like this one, but dynamicly eg.onMouseClick
// color: "blue"
// }
}
}
MouseArea {
id: clickArea
anchors.fill: parent
onClicked: {
console.debug("clicked!")
console.debug("len: " + splitView1.__contents.length); // __contents is the SplitView's default property - an alias to the first child's data property
var newObject = Qt.createQmlObject('import QtQuick 2.1; Rectangle {color: "blue"}',
splitView1, "dynamicSnippet1"); //no effect
// var newObject = Qt.createQmlObject('import QtQuick 2.1; import QtQuick.Layouts 1.0; Rectangle {color: "blue"; width: 50; height: 50}',
// splitView1, "dynamicSnippet1"); //rectangle visible, but not in layout(?) - not resizeable
}
}
}
有沒有什么辦法可以讓我們在SplitView
正確地渲染動態創建的組件作為靜態添加的組件?
似乎API不支持動態插入新元素。 即使你確實讓它工作,它也會成為一個黑客,可能會打破未來的版本。 您可能需要滾動自己的控件來模仿所需的行為。 理想情況下,它應該由某種模型支持。
從QtQuick Controls 1.3開始, SplitView
有一個addItem(item)
方法 。
你必須使用Loader來加載dinamicaly對象。 在onClicked句柄中,你必須聲明sourceComponent屬性來改變Loader的源代碼,如下所示:
ApplicationWindow {
width: 600
height: 400
SplitView {
anchors.fill: parent
Rectangle {
id: column
width: 200
Layout.minimumWidth: 100
Layout.maximumWidth: 300
color: "lightsteelblue"
}
SplitView {
id: splitView1
orientation: Qt.Vertical
Layout.fillWidth: true
Rectangle {
id: row1
height: 200
color: "lightblue"
Layout.minimumHeight: 1
}
Loader {
id:rect
}
}
}
MouseArea {
id: clickArea
anchors.fill: parent
onClicked: {
console.debug("clicked!")
console.debug("len: " + splitView1.__contents.length) // __contents is the SplitView's default property - an alias to the first child's data property
rect.sourceComponent = algo
}
}
Component {
id:algo
Rectangle {
anchors.fill: parent
color: "blue"
}
}
}
我看到了SplitView的源代碼,它在Component.onCompleted信號時計算每個分割區域。 所以我認為這是關鍵點。 無論你怎么做(插入,動態創建)。 插入新區域進行拆分后,不會重置該區域。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.