QML-列表视图项目,显示点击菜单



我正在寻找一些技巧和指针,以显示列表项目下方的菜单时。

如果我有这样的列表模型:

ListModel {
    ListElement {
        name: "Bill Smith"
        number: "555 3264"
    }
    ListElement {
        name: "John Brown"
        number: "555 8426"
    }
    ListElement {
        name: "Sam Wise"
        number: "555 0473"
    }
}

然后是这样的列表视图:

Rectangle {
    width: 180; height: 200
    Component {
        id: contactDelegate
        Item {
            width: 180; height: 40
            Column {
                Text { text: '<b>Name:</b> ' + name }
                Text { text: '<b>Number:</b> ' + number }
            }
        }
    }
    ListView {
        anchors.fill: parent
        model: ContactModel {}
        delegate: contactDelegate
        highlight: Rectangle { color: "lightsteelblue"; radius: 5 }
        focus: true
    }
}

然后,当用户点击项目上时,我想显示菜单:

Menu {
    id: menu
    MenuItem { text: "item1" }
    MenuItem { text: "item2"; }
    MenuItem { text: "item3"; }
}

查看其他一些QML样本,我找到了一些代码,这些代码添加了一个鼠标,并根据窗口定位菜单 - 菜单高度和宽度:

MouseArea {
    anchors.fill: parent
    onClicked: {
        menu.x = (window.width - menu.width) / 2
        menu.y = (window.height - menu.height) / 2
        menu.open();
    }
}

但是我正在努力使它起作用,有人可以指向我的方向正确吗?

如果确定菜单的父级是listView,那么建立通过mapToItem按下的项目的相对位置就足够了:

Rectangle {
    width: 180; height: 200
    Component {
        id: contactDelegate
        Item {
            width: 180; height: 40
            Column {
                Text { text: '<b>Name:</b> ' + name }
                Text { text: '<b>Number:</b> ' + number }
            }
            MouseArea{
                anchors.fill: parent
                onClicked:  {
                    var pos = mapToItem(listView, 0, height)
                    menu.x = pos.x
                    menu.y = pos.y
                    menu.open()
                }
            }
        }
    }
    ListView {
        id: listView
        objectName: "list"
        anchors.fill: parent
        model: ContactModel{}
        delegate: contactDelegate
        focus: true
        Menu {
            id: menu
            MenuItem { text: "item1" }
            MenuItem { text: "item2"; }
            MenuItem { text: "item3"; }
        }
    }
}

完整的示例可以在以下链接中找到。

最新更新