QML自定義樹控制元件(TreeView 的style加上節點可拖動)
阿新 • • 發佈:2018-12-20
-
背景:
前段時間工作需要使用QML的TreeView,要通過拖動節點,對應節點執行對應的操作,查了很多的資料,沒有看到關於節點可拖動的資料,檢視TreeView的原始碼,貌似存在關於節點拖動的地方,但是始終沒有看到可以使用的介面,只好自己動手造輪子了,加上使用過程中踩了不少的坑,也算是給後面用到的人一個案例吧,如果有什麼好的建議,什麼疑問,又或者有好的蘿蔔坑推薦,都可以加這個QQ:995187021,即使沒有解決問題,也可以交個朋友。
-
程式碼:(不知道怎麼描述,就直接看註釋了,有問題加QQ)
MyTreeView.qml
import QtQuick 2.0import QtQuick.Controls 1.4import QtQuick.Controls.Styles 1.4import QtQml.Models 2.2Rectangle{property variant nodePic: ["qrc:/pic/pan.png","qrc:/pic/dir.png","qrc:/pic/file.png"]id:rootTreeView{id:myTreeanchors.fill:parentstyle: treeViewStyleselection: selheaderVisible: false //隱藏列的頭,想知道作用可以註釋掉執行看效果Component.onCompleted: {model = TreeModel.model() //從TreeModel獲取model}itemDelegate:Item{ //節點代理id:treeItemImage { //節點前的圖片id: nodeImgheight: parent.heightwidth: { //不同級的節點圖片寬度不一樣if(styleData.depth==0){return parent.width/6}else if(styleData.depth==1){return parent.width/10}else if(styleData.depth==2){return parent.width/6}}source: { //不同級的節點圖片不一樣if(styleData.depth==0){return nodePic[0]}else if(styleData.depth==1){return nodePic[1]}else if(styleData.depth==2){return nodePic[2]}}}Text{id:itemTextanchors.left: nodeImg.rightanchors.leftMargin: 4anchors.bottom:parent.bottom// elide: styleData.elideModetext:styleData.value //顯示來自model的文字color: styleData.selected ? "#007dff":"white" //選中時字型顏色切換font.pointSize:styleData.selected ? 10:9 //選中時字型大小改變Drag.active: styleData.depth<=1 ? false:itemMosue.drag.active;//一級節點不可拖動Drag.supportedActions: Qt.CopyAction; //選擇複製資料到DropAreaDrag.dragType: Drag.Automatic; //選擇自動開始拖動Drag.mimeData: {"text": text}; //選擇要傳的資料,這裡傳文字MouseArea{ //節點代理的滑鼠事件id:itemMosuehoverEnabled: trueanchors.fill: parentdrag.target: itemTextDrag.onDragStarted: { //控制檯列印開始拖動console.log("start")}onPressed: {sel.setCurrentIndex(styleData.index,0x0010) //點選了文字,選中該節點if(styleData.isExpanded){ //切換節點的展開狀態myTree.collapse(styleData.index)}else{myTree.expand(styleData.index)}}//onReleased: parent.Drag.drop()}}}TableViewColumn { //列title:qsTr("所有通道")role: "text" //顯示的元素width: 200 //列的寬}}ItemSelectionModel { //自定義新增選中id: selmodel: TreeModel.model();}Component {id:treeViewStyle //樹的自定義樣式TreeViewStyle {indentation: 30 //節點間隔branchDelegate: Image { //節點的展開標記圖id:imagesource: styleData.isExpanded ? "qrc:/pic/collapse.png" : "qrc:/pic/expansion.png"width: 9height:9anchors.top:parent.topanchors.topMargin: 2}rowDelegate: Rectangle { //行代理height: 16color:styleData.selected? "#e9fffd" : "#323232" //這裡決定了選中的顏色和背景顏色}}}}
main.qml
import QtQuick 2.7import QtQuick.Window 2.2Window {visible: truewidth: 640height: 480title: qsTr("Hello World")MyTreeView{id:myTreeheight: parent.heightwidth: parent.width/2}Rectangle{id:dropContainerheight: parent.height/2width: parent.width/4anchors.left: myTree.righty:10Text {id: accptedTexttext: qsTr("請拖動樹節點到該矩形框!!!")color: "red"}border.color: "red"border.width: 1DropArea{id:myDropAreaanchors.fill: parentonDropped: {if(drop.supportedActions == Qt.CopyAction){accptedText.text=drop.getDataAsString("text")}}}}}