I am using QtQuick.Controls 2.12 and i am trying to display window with 3 buttons where one of the buttons will have focus. With QtQuick.Controls 1.4 everything is fine and Button1 has focus(blue border):
But with QtQuick.Controls 2.12 this is the result:
If i press Tab focus is passed on Button2, Button3, Button1...
I have also tried with force focus but no result.
This is main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.12
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
RowLayout{
anchors.fill: parent
Button{
id: button1
text: "Button1"
focus: true
}
Button{
text: "Button2"
onClicked: {
button1.forceActiveFocus()
}
}
Button{
text: "Button3"
}
}
}
I am trying to get this when window is started:
The property that allows highlighting is visualFocus
, and if the docs is reviewed:
This property holds whether the control has visual focus. This property is true when the control has active focus and the focus reason is either Qt.TabFocusReason, Qt.BacktabFocusReason, or Qt.ShortcutFocusReason.
In general, for visualizing key focus, this property is preferred over Item::activeFocus. This ensures that key focus is only visualized when interacting with keys - not when interacting via touch or mouse.
See also focusReason and Item::activeFocus.
(emphasis mine)
So you must use forceActiveFocus()
but passing one of the reason indicated because if you do not pass arguments the reason is Qt::OtherFocusReason as the docs points out:
This is an overloaded function.
Forces active focus on the item with the given reason.
This method sets focus on the item and ensures that all ancestor FocusScope objects in the object hierarchy are also given focus.
This method was introduced in Qt 5.1.
See also activeFocus and Qt::FocusReason.
Forces active focus on the item.
This method sets focus on the item and ensures that all ancestor FocusScope objects in the object hierarchy are also given focus.
The reason for the focus change will be Qt::OtherFocusReason. Use the overloaded method to specify the focus reason to enable better handling of the focus change.
See also activeFocus.
(emphasis mine)
So the solution is:
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
RowLayout{
anchors.fill: parent
Button{
id: button1
text: "Button1"
}
Button{
text: "Button2"
}
Button{
text: "Button3"
}
}
Component.onCompleted: button1.forceActiveFocus(Qt.TabFocusReason)
}