QML dialog with focus textField

I am working on a fast qt application and I want to open a dialog. There is a TextField in this dialog box, and I want to focus on this textfiel after opening the dialog. This code works.

function newFolder() { newFolderDialog.visible = true newFolderDialog.open() } Dialog { id: newFolderDialog title: "New folder" height: 150 width: 300 standardButtons: StandardButton.Ok | StandardButton.Cancel Column { anchors.fill: parent Text { text: "Name" height: 40 } TextField { id: newFolderInput width: parent.width * 0.75 focus: true onFocusChanged: console.log("Focus changed " + focus) } } onVisibilityChanged: { if(visible === true){ newFolderInput.text = "" newFolderInput.focus = true } } } 

console output

qml: Focus changed false
qml: Focus changed true
qml: Focus changed false

It seems that once the focus changes after setting the focus to textField

+5
source share
1 answer

You do not need a function because it is written. From the Dialog docs for the open() function:

Shows a dialog to the user. This is equivalent to setting the visible to true.

Given that (this is not a problem), it seems that the focus is constantly being discussed between the dialogue and the contained element. The more you open / close Dialog , the more evaluations occur. I canโ€™t understand why this is happening now. However, you can easily solve the problem: (1) get rid of the onVisibilityChanged handler and (2) rewrite newFolder() . The final code is rewritten:

 ApplicationWindow { width: 360 height: 300 visible: true Button { anchors.centerIn: parent text: "click me!" onClicked: newFolder() } Dialog { id: newFolderDialog title: "New folder" height: 150 width: 300 standardButtons: StandardButton.Ok | StandardButton.Cancel focus: true // Needed in 5.9+ or this code is NOT going to work!! Column { anchors.fill: parent Text { text: "Name" height: 40 } TextField { id: newFolderInput width: parent.width * 0.75 focus: true onFocusChanged: console.log("Focus changed " + focus) } } } function newFolder() { newFolderDialog.open() newFolderInput.focus = true } } 

Thus, you first open the dialog box, and then set the focus to the correct Item .

+6
source

Source: https://habr.com/ru/post/1208176/


All Articles