我有两个几乎相同的qml文件。我在这里列出其中一个,与注释行显示的另一个的差异:
// MessageView.qml; diff. to ThreadView.qml is shown with comment lines
import QtQuick 2.0
Item {
property var model
property var selectedThread: threadsList.currentItem.myThread
property alias spacing: threadsList.spacing
signal activated(var selectedThread)
id: root
ListView {
anchors.fill: parent
id: threadsList
model: root.model
delegate: Rectangle {
property var myThread: message // the other file contains `thread` instead of `message` here
color: threadsList.currentItem == this ? "cyan"
: index % 2 ? "lightblue" : "lightsteelblue"
width: parent.width
height: ti.implicitHeight
MessageItem { // the other file contains `ThreadItem` instead of `MessageItem` here
id: ti
anchors.left: parent.left
anchors.right: parent.right
anchors.verticalCenter: parent.verticalCenter
anchors.margins: 8
}
MouseArea {
anchors.fill: parent
onClicked: {
threadsList.currentIndex = index
activated(root.selectedThread)
}
}
}
}
}
这两个组件旨在是类似外观的列表视图,在委托外观上有细微差别。如何将这两个文件合并为一个以便能够像这样使用它们?
MerdedView {
MessageItem {
// more property customization
}
}
MerdedView {
ThreadItem {
// more property customization
}
}
答案 0 :(得分:1)
委托内部只有很小的差异,因此您需要提取公共代码。例如,MerdedViewDelegate.qml
:
Rectangle {
id: viewItem
property var myThread
//other properties: color, width, height, ...
MouseArea {
anchors.fill: parent
onClicked: {
//use the attached property in ListView
viewItem.ListView.view.currentIndex = index
}
}
}
然后像MergedView.qml
一样创建MessageView.qml
,除了委托现在更改为别名属性:
//MergedView.qml
Item {
property alias delegate: threadsList.delegate
//other properties
ListView {
anchors.fill: parent
id: threadsList
model: root.model
}
}
最后,您可以像这样编写QML:
MergedView {
delegate: MergedViewDelegate{
myThread: message //or something similar
MessageItem { /* ... */ }
}
}
MergedView {
delegate: MergedViewDelegate{
myThread: thread
ThreadItem { /* ... */ }
}
}