MCoder
MCoder

Reputation: 126

How to hide menu items in QML

I'm using Qt Quick Controls 2 and write this code for context menu:

Menu{
    id: contextmenu
    x: ( parent.width - contextmenu.width ) / 2
    y: ( parent.height - contextmenu.height ) / 2
    modal: true

    property int selid

    MenuItem {
        text: "Compare"
        visible: isexp
    }
    Divider{ visible: isexp }
    MenuItem {
        text: "Send..."
        visible: isexp
    }
    Divider{ visible: isexp }
    MenuItem {
        text: "Edit..."
    }
    Divider{}
    MenuItem {
        text: "Delete"
    }
}

Divider - it is my component. isexp is is property of object. When isexp false menu is shows wrong. See screenshot: https://s31.postimg.org/c608kdtbv/qqq.png

How to change visibility of menu items and show menu properly. Thank for advice.

Upvotes: 5

Views: 6793

Answers (3)

My_Cat_Jessica
My_Cat_Jessica

Reputation: 133

In early Qt quick version, like Controls 1.4, you can use the private method of the menu object: __closeAndDestroy().

But there is no guarantee for this private method.

Upvotes: -1

Mitch
Mitch

Reputation: 24406

Setting the height to 0 in addition to hiding the items works:

import QtQuick 2.6
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    property bool itemsVisible: true

    Menu {
        id: contextmenu
        x: (parent.width - contextmenu.width) / 2
        y: (parent.height - contextmenu.height) / 2
        modal: true

        MenuItem {
            text: "Compare"
            visible: itemsVisible
            height: visible ? implicitHeight : 0
        }
        MenuItem {
            text: "Send..."
            visible: itemsVisible
            height: visible ? implicitHeight : 0
        }
        MenuItem {
            text: "Edit..."
        }
        MenuItem {
            text: "Delete"
        }
    }

    Button {
        text: "Open"
        onClicked: {
            itemsVisible = !itemsVisible
            contextmenu.open()
        }
    }
}

This is because the height of the menu is based off the contentHeight of the internal ListView.

Upvotes: 7

MCoder
MCoder

Reputation: 126

I found workaround but it is not so good:

Menu{
    id: contextmenu
    x: ( parent.width - contextmenu.width ) / 2
    y: ( parent.height - contextmenu.height ) / 2
    modal: true

    MenuItem {
        text: "Compare"
    }
    Divider{ }
    MenuItem {
        text: "Send..."
    }
    Divider{ }

    MenuItem {
        text: "Edit..."
    }
    Divider{}
    MenuItem {
        text: "Delete"
    }

    Component.onCompleted: {
        if( !isexp )
        {
            contextmenu.removeItem(0)
            contextmenu.removeItem(0)
            contextmenu.removeItem(0)
            contextmenu.removeItem(0)
        }
    }
}

Upvotes: -1

Related Questions