Search code examples
qtqmlqt5qtquick2qt-quick

QML - ListView item which displays a menu on tap


I'm looking for some tips and pointers on displaying a menu underneath a list Item when a user taps on the Item.

If I have a ListModel like this:

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

Then a ListView like so:

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

Then when a user taps on an Item I want to display a menu:

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

Looking at some other QML samples I've found some code which adds a MouseArea and positions the menu based on Window - Menu height and width:

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

However I'm struggling to get it working, can anyone point me in the right direction?


Solution

  • If it is established that the parent of the Menu is the ListView, then it will only suffice to establish a relative position of the item pressed through 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"; }
            }
    
        }
    }
    

    The complete example can be found in the following link.