最近使用到Treeview,需要添加一個功能,右鍵菜單。
他默認的clicked以及其他信號都不支持右鍵。Treeview的源碼裏面沒有添加。
點擊左鍵的時候,Treeview會選中那一行,如果添加右鍵,沒有對應的函數和屬性來選擇這一行。
一、剛開始的時候我下載源碼,重新編譯了Treeview,讓他支持右鍵
修改源碼,給MouseArea增加 acceptedButtons: Qt.LeftButton | Qt.RightButton
增加一個右鍵點擊的信號signal clickedR(var index, var mouse),mouse屬性是爲了獲取mouse的位置方便顯示菜單。
然後再onclicked裏面判斷鼠標,發送該信號。
二、使用下面這種代碼,不需要編譯源碼,主要查看源碼
TreeView {
id: id_tree_view
anchors.left: parent.left
anchors.right: parent.right
anchors.rightMargin: 1
anchors.top: id_scan_btn.bottom
anchors.topMargin: 1
anchors.bottom: parent.bottom
backgroundVisible: false
headerVisible:false //不顯示錶頭
horizontalScrollBarPolicy: Qt.ScrollBarAlwaysOff //關閉橫向滾動條
model: TreeModel
frameVisible: false //背景爲深色的時候 會有一條白邊,false時消除邊
TableViewColumn {
title: "Name"
role: "name_role"
resizable: false
width: id_tree_view.width
}
style: TreeViewStyle {
backgroundColor: "#20252A"
itemDelegate: Rectangle{
height: 28
//背景設置透明,不然在選中行的時候會出現選中顏色就一半的情況
color: styleData.depth === 0 ? "#3C454E" : "transparent"
Text {
color: "white"
elide: styleData.elideMode
text: styleData.value
anchors.verticalCenter: parent.verticalCenter
}
Image {
source: "qrc:///res/navi/add.png"
anchors.verticalCenter: parent.verticalCenter
anchors.right: parent.right
anchors.rightMargin: 12
visible: styleData.depth === 0
}
}
rowDelegate: Rectangle{
id: rowDel
color: styleData.selected ? "#595F69" : "transparent";
height: 28
}
//重寫三角
branchDelegate: Rectangle {
width: 20
height: 28
color: styleData.depth === 0 ? "#3C454E" : "transparent"
Image {
anchors.centerIn: parent
source: styleData.isExpanded ? "qrc:///res/navi/triangle_gray_open.png" :
"qrc:///res/navi/triangle_gray_normal.png"
width: sourceSize.width
height: sourceSize.height
}
}
}
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.LeftButton | Qt.RightButton
onClicked: {
//選中當前行 -- 關鍵代碼,來自源碼裏面
var pressedRow = id_tree_view.__listView.indexAt(0, mouseY + id_tree_view.__listView.contentY)
id_tree_view.__listView.currentIndex = pressedRow
if(mouse.button === Qt.RightButton) {
var index = parent.indexAt(mouse.x, mouse.y)
if (index.valid) {
//打開菜單
id_navi_menu.x = mouse.x
id_navi_menu.y = mouse.y + id_tree_view.y
id_navi_menu.open()
}
}
}
onDoubleClicked: {
if(mouse.button === Qt.LeftButton) {
var index = parent.indexAt(mouse.x, mouse.y)
if (index.valid) {
if(id_tree_view.isExpanded(index))
id_tree_view.collapse(index)
else
id_tree_view.expand(index)
}
}
}
}
}