Add context menu for text fields and areas

This commit is contained in:
miruka
2020-07-10 00:02:43 -04:00
parent 657b700fcd
commit 612ded755a
8 changed files with 118 additions and 0 deletions

View File

@@ -93,6 +93,8 @@ TextArea {
event.modifiers & Qt.MetaModifier
) event.accepted = true
Keys.onMenuPressed: contextMenu.spawn(false)
// Prevent leaking arrow presses to parent elements when the carret is at
// the beginning or end of the text
Keys.onLeftPressed: event.accepted = cursorPosition === 0 && ! selectedText
@@ -145,4 +147,17 @@ TextArea {
Behavior on opacity { HNumberAnimation {} }
}
TapHandler {
acceptedButtons: Qt.RightButton
acceptedPointerTypes: PointerDevice.GenericPointer | PointerDevice.Pen
onTapped: contextMenu.spawn()
}
TapHandler {
acceptedPointerTypes: PointerDevice.Finger | PointerDevice.Pen
onLongPressed: contextMenu.spawn()
}
HTextContextMenu { id: contextMenu }
}

View File

@@ -0,0 +1,73 @@
// SPDX-License-Identifier: LGPL-3.0-or-later
import QtQuick 2.12
HMenu {
property Item control: parent // HTextField or HTextArea
property bool hadPersistentSelection: false // TODO: use a Qt 5.15 Binding
function spawn(atMousePosition=true) {
hadPersistentSelection = control.persistentSelection
control.persistentSelection = true
atMousePosition ?
popup() :
popup(
control.cursorRectangle.right,
control.cursorRectangle.bottom + theme.spacing / 4,
)
}
onClosed: control.persistentSelection = hadPersistentSelection
Component.onDestruction:
control.persistentSelection = hadPersistentSelection
HMenuItem {
icon.name: "undo"
text: qsTr("Undo")
enabled: control.canUndo
onTriggered: control.undo()
}
HMenuItem {
icon.name: "redo"
text: qsTr("Redo")
enabled: control.canRedo
onTriggered: control.redo()
}
HMenuSeparator {}
HMenuItem {
icon.name: "cut-text"
text: qsTr("Cut")
enabled: control.selectedText
onTriggered: control.cut()
}
HMenuItem {
icon.name: "copy-text"
text: qsTr("Copy")
enabled: control.selectedText
onTriggered: control.copy()
}
HMenuItem {
icon.name: "paste-text"
text: qsTr("Paste")
enabled: control.canPaste
onTriggered: control.paste()
}
HMenuSeparator {}
HMenuItem {
icon.name: "select-all-text"
text: qsTr("Select all")
onTriggered: control.selectAll()
}
}

View File

@@ -66,6 +66,8 @@ TextField {
event.modifiers & Qt.MetaModifier
) event.accepted = true
Keys.onMenuPressed: contextMenu.spawn(false)
// Prevent leaking arrow presses to parent elements when the carret is at
// the beginning or end of the text
Keys.onLeftPressed: event.accepted = cursorPosition === 0 && ! selectedText
@@ -143,4 +145,17 @@ TextField {
Behavior on opacity { HNumberAnimation {} }
}
TapHandler {
acceptedButtons: Qt.RightButton
acceptedPointerTypes: PointerDevice.GenericPointer | PointerDevice.Pen
onTapped: contextMenu.spawn()
}
TapHandler {
acceptedPointerTypes: PointerDevice.Finger | PointerDevice.Pen
onLongPressed: contextMenu.spawn()
}
HTextContextMenu { id: contextMenu }
}