Leaving text editing when clicking outside TextArea but enable clicking inside TextArea at the same time
-
Hey,
I've been trying to solve the problem with hiding the keyboard on phone or simply leaving the text editing mode when clicking outside active TextArea. I've found the solution where creating invisible MouseArea can be used which is raised to high z value when editing TextArea. Clicking on it then disables focus on the TextArea. This works well except I cannot click to a different position in the text without leaving the edit mode and getting back to it nor can I select the text by holding. Anybody has any suggestions how to solve this? My idea was to keep the TextArea with higher z value as the MouseArea helper layer but for some reason it doesn't work. Here's the code://helper layer MouseArea { id: outFocuser anchors.fill: parent z: -999 onClicked: {outFocuser.z=-999; outFocuser.forceActiveFocus();} } TextArea{ onActiveFocusChanged: {if (activeFocus) {outFocuser.z=998; this.z=999;} else {deselect(); this.z=1;}} }
Thanks for reading and have a great day!
-
Alright after some research I probably found a workaround to fix this. I got help and inspiration here. The problem is that sometimes when the elements are stored in containers such as ScrollView the z-order thing doesn't work well plus the container can catch mouse event not allowing it to propagate to the helper MouseArea. In such cases all the problematic elements need to contain TapHandler which allows to catch the click event and do custom action. So for example:
ScrollView { TapHandler { onTapped: outFocuser.forceActiveFocus();} }
In this way no z-order tricks are needed nor the onActiveFocusChanged property in TextArea.