右键单击TableView行时,我想显示一个上下文菜单。我尝试了这段代码:

import QtQuick 2.0
import QtQuick.Controls 1.0

TableView { id: tableView
    width: 300
    height: 200

    TableViewColumn { role: 'a'; title: 'a'; width: 50 }
    TableViewColumn { role: 'b'; title: 'b'; width: 50 }
    model: ListModel {
        ListElement { a: 1; b: 2 }
        ListElement { a: 3; b: 4 }
        ListElement { a: 5; b: 6 }
        ListElement { a: 7; b: 8 }
        ListElement { a: 9; b: 10 }
        ListElement { a: 11; b: 12 }
    }

    Menu { id: contextMenu
        MenuItem {
            text: qsTr('Delete')
        }
    }

    rowDelegate: Item {
        Rectangle {
            anchors {
                left: parent.left
                right: parent.right
                verticalCenter: parent.verticalCenter
            }
            height: parent.height
            color: styleData.selected ? 'lightblue' : 'white'
            MouseArea {
                anchors.fill: parent
                propagateComposedEvents: true
                onReleased: {
                    if (typeof styleData.row === 'number') {
                        tableView.currentRow = styleData.row
                        if (mouse.button === Qt.RightButton) { // never true
                            contextMenu.popup()
                        }
                    }
                    mouse.accepted = false
                }
            }
        }
    }
}

由于右键单击不调用onReleased处理程序,因此未显示上下文菜单。

我按照here文档中的建议使用了propagateComposedEventsmouse.accepted = false,但是无论如何它都无法正常工作,而且我不认为onReleased是一个组合事件。

我需要帮助以使上面的代码按预期工作。

谢谢你。

最佳答案

看起来可以更轻松地完成此操作:

MouseArea {
    anchors.fill: parent
    acceptedButtons: Qt.LeftButton | Qt.RightButton
    onClicked: {
        console.log("Click")
        if (mouse.button == Qt.LeftButton)
        {
            console.log("Left")
        }
        else if (mouse.button == Qt.RightButton)
        {
            console.log("Right")
        }
    }
}

09-10 04:33
查看更多