wordpress主题 站长,网上做一道题2元的网站,苏州建设网站电话,typecho迁移wordpress背景
感觉QML自带的TreeView不是很好用#xff0c;用在文件路径树形结构比较多#xff0c;但是想用在自己数据里#xff0c;就不太方便了#xff0c;所以自己做一个。
用‘ListView里迭代ListView’的方法#xff0c;制作树形结构#xff0c;成果图#xff1a;
代码…背景
感觉QML自带的TreeView不是很好用用在文件路径树形结构比较多但是想用在自己数据里就不太方便了所以自己做一个。
用‘ListView里迭代ListView’的方法制作树形结构成果图
代码
新建一个MyTreeView.qml用来写主要代码再在main.qml中调用MyTreeView并为它填充数据。 这里数据是在qml中用JSON.parse构建的json数据也可以在cpp中用QJsonArray和QJsonObject来构建数据。
// MyTreeView.qml
import QtQuick 2.0Item {id: rootproperty alias model: list_view.modelListView {id: list_viewwidth: contentWidthanchors.fill: parentanchors.margins: 10delegate: list_delegate}Component {id: list_delegateItem{id: list_itemgroupwidth: leftLine.width centre.width rightLine.width listView.widthheight: Math.max(centre.height, listView.height)property int lineY: leftLine.yRectangle {id: leftLinewidth: 20height: 1color: #d3dee4visible: modelData.id 0anchors.verticalCenter: centre.verticalCenter}Rectangle {id: centrewidth: 150height: 50color: #d3dee4radius: 5anchors.left: leftLine.rightanchors.verticalCenter: parent.verticalCenterText {text: qsTr(modelData.name)font.pixelSize: 20font.bold: trueanchors.centerIn: parent}}Rectangle {id: rightLinewidth: 20height: 1color: #d3dee4visible: modelData.subnodes.length 0anchors.verticalCenter: centre.verticalCenteranchors.left: centre.right}Rectangle {id: verticalLinewidth: 1color: #d3dee4x: parent.width 1visible: modelData.subnodes.length 1anchors.top: parent.topanchors.bottom: parent.bottom}ListView {id: listViewdelegate: list_delegateheight: contentHeightwidth: contentWidthanchors.right: parent.rightmodel: modelData.subnodesspacing: 10onModelChanged: {}}Component.onCompleted: {listView.forceLayout() // 要先确保listView加载子项完成// 画一下verticalLine的y坐标起点和终点for (var i 0; i modelData.subnodes.length; i) {var item listView.itemAtIndex(i)if (i 0) {verticalLine.anchors.topMargin item.lineY} else if (i modelData.subnodes.length-1) {verticalLine.anchors.bottomMargin item.lineY}}}}}
}
// main.qml
import QtQuick 2.15
import QtQml.Models 2.15
import QtQuick.Window 2.12
import QtQuick.Controls 1.4Window {id: window_width: 940height: 680visible: truetitle: qsTr(Hello World)color: #103e6fItem {id: homeanchors.fill: parentMyTreeView {id: treeViewanchors.fill: parent}}Component.onCompleted: {var data JSON.parse([{id: -1,name: 目录,subnodes: [{id: 0,name: 第一本书,subnodes: [{id: 1,name: 第一章,subnodes: [{id: 2,name: 第一节,subnodes: []}, {id: 3,name: 第二节,subnodes: []}]}, {id: 4,name: 第二章,subnodes: [{id: 5,name: 第一节,subnodes: []}, {id: 6,name: 第二节,subnodes: []}, {id: 7,name: 第三节,subnodes: []}]}]}, {id: 8,name: 第二本书,subnodes: [{id: 9,name: 第一章,subnodes: [{id: 10,name: 第一节,subnodes: []}, {id: 11,name: 第二节,subnodes: []}]}, {id: 12,name: 第二章,subnodes: [{id: 13,name: 第一节,subnodes: []}]}]}]}])treeView.model data}}