【问题标题】:How to show a context menu on right click in TableView rowDelegate如何在 TableView rowDelegate 中右键单击时显示上下文菜单
【发布时间】:2013-12-07 22:42:11
【问题描述】:

我想在右键单击 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 不是一个组合事件。

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

谢谢。

【问题讨论】:

    标签: qt qml qt-quick qtquick2 qt5.1


    【解决方案1】:

    看起来这可以更容易地完成:

    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.RightButton。这样就解决了问题。
    • 如果发现只设置“acceptedButtons: Qt.RightButton”效果最好。否则,左键单击不会向上传播,您无法选择行。
    猜你喜欢
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2017-03-24
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多