The QML TextArea
inherits onEditingFinished
From TextEdit
where it is triggered on losing focus or an enter/return press. (assuming no input validation)
However one cannot trigger onEditingFinished from a TextArea
with Enter
unlike for TextEdit
as it is captured for a line break.
Additionally in a window with a single field it can be a unintuitive to remove focus from the TextArea
as background and most other Controls don't accept focus so the user has to click off the window or clicking the menu bar.
How can I improve the user experience for triggering actions once they have edited a multiline string input field? Is linebreaks inputted with Ctrl Enter
, with editing completion on Enter
an option, and if so how would this be implemented?
Here is the example QML of this scenario:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.3
Window {
visible: true
width: 640; height: 480
title: qsTr("Hello World")
Column {
TextArea {
implicitHeight: 200
placeholderText: qsTr("Enter description")
onEditingFinished: console.log("Editing complete")
}
Label {text: qsTr("Label")}
}
}
CodePudding user response:
You can override the Return key press event and handle it however you want. If you want to use the Ctrl Return, check the modifiers
property in the event.
TextArea {
implicitHeight: 200
placeholderText: qsTr("Enter description")
onEditingFinished: console.log("Editing complete")
Keys.onReturnPressed: {
if (event.modifiers & Qt.ControlModifier) {
// Ctrl Return
editingFinished();
}
else {
// Ignore other cases
event.accepted = false;
}
}
}
Or if you want to use the Return key without pressing Ctrl, then you can simply do this:
TextArea {
implicitHeight: 200
placeholderText: qsTr("Enter description")
onEditingFinished: console.log("Editing complete")
Keys.onReturnPressed: {
editingFinished();
}
}
CodePudding user response:
You can do it by handling the simple ReturnPressed
and ctrl ReturnPressed
or Shift ReturnPressed
event by yourself.
In the code below I've used Shift ReturnPressed
for new line:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.3
Window {
visible: true
width: 640; height: 480
title: qsTr("Hello World")
Column {
TextArea {
id: text_area
implicitHeight: 200
placeholderText: qsTr("Enter description")
Keys.onReturnPressed: {
if(Qt.ShiftModifier)
console.log("Editing complete")
else {
text = '\n'
text_area.cursorPosition = text_area.length
}
}
}
Label {text: qsTr("Label")}
}
}