En esta página

ContextMenu QML Type

El tipo asociado ContextMenu permite abrir un menú contextual de forma adecuada para cada plataforma. Más información...

Import Statement: import QtQuick.Controls
Since: Qt 6.9

Propiedades

Señales

Descripción detallada

ContextMenu se puede asociar a cualquier objeto ` item ` para mostrar un menú contextual ante un evento específico de la plataforma, como un clic con el botón derecho o la tecla de menú contextual.

Pane {
    anchors.fill: parent

    ContextMenu.menu: Menu {
        MenuItem {
            text: qsTr("Eat Tomato")
            onTriggered: { /* ... */ }
        }
        MenuItem {
            text: qsTr("Throw Tomato")
            onTriggered: { /* ... */ }
        }
        MenuItem {
            text: qsTr("Squash Tomato")
            onTriggered: { /* ... */ }
        }
    }
}

Compartir menús contextuales

Es posible compartir un objeto ` Menu ` entre varios objetos de menú contextual asociados. Esto permite reutilizar un único menú cuando los elementos que necesitan menús contextuales tienen datos en común. Por ejemplo:

pragma ComponentBehavior: Bound

import QtQuick
import QtQuick.Controls.Basic
import QtQuick.Templates as T

ApplicationWindow {
    width: 600
    height: 400
    visible: true

    component Tomato: Label {
        id: tomato
        objectName: text
        horizontalAlignment: Label.AlignHCenter
        verticalAlignment: Label.AlignVCenter
        width: Math.max(200, contentWidth * 1.5, contentWidth * 1.5)
        height: width
        color: skinColor

        function eat() { print("Ate " + text) }
        function ditch() { print("Threw " + text) }
        function squash() { print("Squashed " + text) }

        property color skinColor: "tomato"

        background: Rectangle {
            color: tomato.skinColor
            radius: width / 2
        }

        ContextMenu.menu: contextMenu
    }

    Menu {
        id: contextMenu

        readonly property Tomato triggerItem: parent as Tomato
        readonly property string triggerItemText: triggerItem?.text ?? ""

        MenuItem {
            text: qsTr("Eat %1").arg(contextMenu.triggerItemText)
            onTriggered: contextMenu.triggerItem.eat()
        }
        MenuItem {
            text: qsTr("Throw %1").arg(contextMenu.triggerItemText)
            onTriggered: contextMenu.triggerItem.ditch()
        }
        MenuItem {
            text: qsTr("Squash %1").arg(contextMenu.triggerItemText)
            onTriggered: contextMenu.triggerItem.squash()
        }
    }

    Row {
        anchors.centerIn: parent

        Tomato {
            text: qsTr("tomato")
        }

        Tomato {
            text: qsTr("really ripe tomato")
            skinColor: "maroon"
        }
    }
}

Rendimiento

ContextMenu crea su ` Menu ` de forma diferida, solo cuando se solicita. Si no fuera por esta optimización, el ` Menu ` se crearía al cargarse el componente que lo contiene, lo que suele ocurrir al iniciar la aplicación.

Se recomienda no asignar un identificador al objeto ` Menu ` asignado a la propiedad ` menu ` de `ContextMenu` en el momento de su definición. Hacerlo impediría esta optimización. Por ejemplo:

Pane {
    anchors.fill: parent

    ContextMenu.menu: Menu {
        // This prevents lazy creation of the Menu.
        id: myMenu

        // ...
    }
}

El ejemplo de la sección « Sharing context menus » funciona porque el « Menu » se define por separado de su asignación.

Interacción con otros menús

Si se abre un « Menu » (por ejemplo, mediante un « TapHandler » u otros medios), ContextMenu no se abrirá al mismo tiempo. Esto permite que las aplicaciones heredadas, escritas antes de la introducción de ContextMenu, sigan funcionando como se espera.

Compatibilidad con menús nativos

ContextMenu cuenta con el respaldo de un menú nativo en iOS.

Nota: si asignas tu propio ` menu`, debes establecer ` popupType ` en ` Popup.Native ` para garantizar la compatibilidad con el menú nativo.

Documentación de propiedades

Esta propiedad contiene el menú contextual que se abrirá. Se puede asignar cualquier objeto ` Menu `.

Nota: No se puede asignar un identificador (id)al objeto ` Menu ` asignado a esta propiedad. Para obtener más información, consulta Sharing context menus.

Documentación de Signal

requested(point position)

Esta señal se emite cuando se solicita un menú contextual.

Si se ha solicitado mediante un clic con el botón derecho del ratón, ` position ` proporciona la posición del clic con respecto al elemento padre.

El siguiente ejemplo muestra cómo abrir un menú contextual mediante programación:

Button {
    id: button
    text: qsTr("Click me!")
    ContextMenu.onRequested: position => {
        const menu = buttonMenu.createObject(button)
        menu.popup(position)
    }
}

Component {
    id: buttonMenu
    Menu {
        MenuItem { text: qsTr("Open") }
    }
}

Si no se ha configurado ningún menú, pero esta señal está conectada, el evento del menú contextual se aceptará y no se propagará.

Nota: El controlador correspondiente es ` onRequested`.

Véase también QContextMenuEvent::pos().

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.