首页 文章

QML - ListView项目,用于显示菜单

提问于
浏览
0

当用户点击项目时,我正在寻找关于在列表项目下显示菜单的一些提示和指示 .

如果我有这样的ListModel:

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

然后像这样的ListView:

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,并根据Window - 菜单高度和宽度定位菜单:

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

然而,我正在努力让它发挥作用,有人能指出我正确的方向吗?

1 回答

  • 1

    如果确定菜单的父级是ListView,那么只需通过 mapToItem Build 按下的项目的相对位置即可:

    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"; }
            }
    
        }
    }
    

    完整的示例可以在以下link中找到 .

相关问题