Qt QML从外部指定ListView委托属性



我有一个ChoicePage.qml,如下所示:

import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
Item {
property alias searchBar: searchBar
property alias model: listView.model
property alias itemDelegate: listView.delegate
ColumnLayout {
height: parent.height
width: parent.width * 0.9
anchors.horizontalCenter: parent.horizontalCenter
TextField {
id: searchBar
Layout.preferredHeight: parent.height * 0.1
Layout.preferredWidth: parent.width
placeholderText: qsTr("Search..")
}
ListView {
id: listView
Layout.fillHeight: true
Layout.preferredWidth: parent.width
ScrollBar.vertical: ScrollBar {}
clip: true
spacing: height * 0.01
}
}
}

还有一个TestChoicePage.qml,如下所示:

import QtQuick 2.0
ChoicePage {
model: proxy.list // c++ proxy that expose a list of QObject*
itemDelegate: RadioButton {
height: ListView.view.height * 0.1
width: ListView.view.width
text: modelData.description
}
}

我希望在ChoicePage中包含RadioButton委托项,并从TestChoicePage、Test2ChoicePage等中定义modelData.description或页面所需的其他内容。
是否可能?

不能在委托之外访问模型的数据。任何与模型相关的绑定都必须在委托中定义。

委托的非模型相关属性可以从外部进行控制
可以在委托外部定义新属性。这些新属性可以绑定到委托的属性。

参见以下示例:

List.qml:
ListView {
width: 200
height: 200
spacing: 5
property string rectColor: ""
delegate: Rectangle{
width: parent.width
height: parent.height / 5
color: rectColor
required property string modelProperty
RadioButton{
text: parent.modelProperty
}
}
}  
main.qml:
MyList{
model: myCppList
rectColor: "green"
}

最新更新