Button 当激活QML选项卡而不是文本字段时,如何确保按钮具有焦点?
在QML中,我有一个包含文本字段和按钮的选项卡。当选择选项卡而不是文本字段时,如何确保按钮具有焦点?将“focus:”分别设置为true和false并不起作用。在下面的代码中,目标是btnRefresh在选择选项卡时具有焦点,而不是txtName main.qml:Button 当激活QML选项卡而不是文本字段时,如何确保按钮具有焦点?,button,focus,qml,textfield,Button,Focus,Qml,Textfield,在QML中,我有一个包含文本字段和按钮的选项卡。当选择选项卡而不是文本字段时,如何确保按钮具有焦点?将“focus:”分别设置为true和false并不起作用。在下面的代码中,目标是btnRefresh在选择选项卡时具有焦点,而不是txtName main.qml: import QtQuick 2.2 import QtQuick.Controls 1.1 import QtQuick.Layouts 1.1 import QtQuick.Controls.Styles 1.2 // For
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1
import QtQuick.Controls.Styles 1.2 // For TabViewStyle
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
TabView {
id: tabView
anchors.fill: parent
anchors.margins: 20
tabPosition: Qt.BottomEdge
Tab {title: "Tab 1"; source: "mytab.qml"}
Tab {title: "Tab 2"; source: "mytab.qml"}
style: TabViewStyle {
frameOverlap: 1
tab: Rectangle {
color: styleData.selected ? "steelblue" :"lightsteelblue"
border.color: "steelblue"
implicitWidth: Math.max(text.width + 4, 80)
implicitHeight: 20
radius: 2
Text {
id: text
anchors.centerIn: parent
text: styleData.title
color: styleData.selected ? "white" : "black"
}
}
frame: Rectangle { color: "steelblue" }
}
}
}
mytab.qml:
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Layouts 1.1
Rectangle {
anchors.fill: parent
GridLayout {
columns: 2
anchors.fill: parent
rowSpacing: 10
RowLayout {
Layout.columnSpan: 2
Label {
id: lblName
text: "Name:"
}
TextField {
id: txtName;
text: "a name"
Layout.preferredWidth: lblName.implicitWidth * 1.5;
focus: false
}
}
TextArea {
id: textSetup
text: "Text Area"
Layout.columnSpan: 2
Layout.fillWidth: true
Layout.fillHeight: true
}
Button {
id: btnRefresh
Layout.columnSpan: 2
Layout.alignment: Qt.AlignHCenter
text: qsTr("Refresh")
focus: true
}
}
}
无论何时在选项卡视图中切换选项卡,都会在两个选项卡(一个消失,一个出现)上调用信号处理程序
onVisibleChanged
,因为这些选项卡的可见性已更改。您可以尝试将以下代码添加到选项卡:
Tab {
id: tab1
title: "Tab 1"; source: "mytab.qml"
onVisibleChanged: {
if (visible) tab1.item.funcSetFocusOnButton();
}
}
请注意使用item
在选项卡上调用函数的方式。
现在在“mytab.qml”中,您创建了一个javascript函数funcSetFocusOnButton
,它将焦点设置在您的按钮上。因此,您的mytab.qml将具有以下附加代码:
Rectangle {
//Your GridLayout{}
funcSetFocusOnButton() {
btnRefresh.forceActiveFocus();
}
}
请注意,函数
funcSetFocusOnButton
应该是基本项(此处为矩形)的直接子项。希望这有帮助 你能编辑你的问题来添加代码来证明它做不到吗?我更新了问题以显示对选项卡的依赖,并提供了代码示例。