ContextMenu QML Type
El tipo de adjunto ContextMenu proporciona una forma de abrir un menú contextual de una manera apropiada para la plataforma. Más...
| Import Statement: | import QtQuick.Controls |
| Since: | Qt 6.9 |
Propiedades
- menu : Menu
Señales
- requested(point position)
Descripción detallada
ContextMenu puede adjuntarse a cualquier item para mostrar un menú contextual ante un evento específico de la plataforma, como un clic derecho o la tecla del 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 Menu entre varios objetos de menú contextual adjuntos. 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 perezosamente su Menu sólo cuando se le solicita. Si no fuera por esta optimización, el Menu se crearía cuando se está cargando el componente que lo contiene, lo que suele ocurrir al iniciar la aplicación.
Se recomienda no dar un id al Menu asignado a la propiedad menu de ContextMenu cuando se define donde se asigna. Hacerlo evita 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 está definido separadamente de su asignación.
Interacción con otros menús
Si se abre un Menu a través de, por ejemplo, un TapHandler u otro medio, ContextMenu no se abrirá al mismo tiempo. Esto permite que las aplicaciones heredadas que se escribieron antes de que se introdujera ContextMenu sigan funcionando como se esperaba.
Menú nativo
ContextMenu está respaldado por un menú nativo en iOS.
Nota: si asigna su propio menu, debe establecer popupType en Popup.Native para garantizar la compatibilidad con el menú nativo.
Documentación de propiedades
menu : Menu
Esta propiedad contiene el menú contextual que se abrirá. Puede establecerse a cualquier objeto Menu.
Nota: El Menu asignado a esta propiedad no puede tener un id. Consulte Sharing context menus para obtener más información.
Documentación sobre señales
requested(point position)
Esta señal se emite cuando se solicita un menú contextual.
Si se solicita haciendo clic con el botón derecho del ratón, position indica la posición del clic en relación con el elemento principal.
El siguiente ejemplo muestra cómo abrir mediante programación un menú contextual:
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 hay menú, pero esta señal está conectada, el evento de menú contextual será aceptado y no se propagará.
Nota: El manejador 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.