Remember the last focused TextEdit and insert text inside it on clicking a button.
-
Dear Qt
Suppose I have several
TextInputfields and a button. Clicking the button should insert some text (let say "foo") inside the text field that had the focus right before clicking the button. I was thinking of the two following approaches:Approach #1
- We have a property
var lastFocusedTextwhich is intended to store the last focused text field - Once the user changes the focus of a text field the
lastFocusedTextis updated - On clicking we check if
lastFocusedTextis valid and if so dotext = "boo"
This is a sketch of what I mean :
Item { id: root TextInput { id: textA onActiveFocusChanged : { if(activeFocus === true) { root.lastFocusedText = textA } else { root.lastFocusedText = null } } } TextInput { id: textB onActiveFocusChanged : { if(activeFocus === true) { root.lastFocusedText = textB } else { root.lastFocusedText = null } } } Button { focusPolicy: Qt.NoFocus onClicked : { if(root.lastFocusedText instanseof TextInput) { root.lastFocusedText.text = "Foo" } } } }Approach #2
This one is more simple :
Every text field is subscribed to a signal and if it has active focus changes its text:
Item { id: root TextInput { id: textA Connections { target: booButton function onClicked() { if(textA.activeFocus === true) { textA.text = "Foo" } } } } TextInput { id: textB Connections { target: booButton function onClicked() { if(textB.activeFocus === true) { textB.text = "Foo" } } } } Button { id: booButton focusPolicy: Qt.NoFocus } }I like second approach more. But what do you think ?
- We have a property
-
Another alternative would be to use the
Window.activeFocusItemattached property. On button click, check if it's one one your TextInput (item.parent === root && item.instanceof TextInput) and set its text.Reading the code I prefer to have an
onClickedin theButton, to keep the cause and effects close together.