Qt 如何在TableView行委派中单击鼠标右键时显示关联菜单

Qt 如何在TableView行委派中单击鼠标右键时显示关联菜单,qt,qml,qt-quick,qtquick2,qt5.1,Qt,Qml,Qt Quick,Qtquick2,Qt5.1,我想在右键单击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:

我想在右键单击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
处理程序

我使用了文档中建议的
propagateComposedEvents
mouse.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")
        }
    }
}

谢谢我必须添加到代码中的唯一一行是
acceptedButtons:Qt.LeftButton | Qt.righButton
。这就解决了问题。如果发现只有设置“acceptedButtons:Qt.RightButton”效果最好。否则,左键单击不会向上传播,您无法选择行。