强制焦点到 ListView 中的 TextEdit
Force focus to TextEdit in ListView
考虑以下示例。
Rectangle {
height: 200
width: 200
ListView {
id: lv
anchors.fill: parent
model: ListModel {
ListElement {
name: "aaa"
}
ListElement {
name: "bbb"
}
ListElement {
name: "ccc"
}
}
delegate: TextEdit {
id: delegate
text: name
width: 200
height: 100
activeFocusOnPress: false
onActiveFocusChanged: {
if(activeFocus) {
font.italic = true;
} else {
font.italic = false;
}
}
MouseArea {
anchors.fill: parent
onDoubleClicked : {
delegate.focus = true;
lv.currentIndex = index;
}
}
}
}
}
我希望能够通过双击激活 TextEdit。如果它在列表视图之外,它会按预期工作,但在列表视图中它不起作用。
我猜问题是列表视图是焦点范围,但我不知道如何解决它。
提前致谢。
你可以利用 forceActiveFocus
:
This method sets focus on the item and ensures that all ancestor FocusScope objects in the object hierarchy are also given focus.
您可以使用重载版本(不带参数)或带有 FocusReason
的版本。这是使用后者的代码的修改版本。我还做了两个小调整,并附上解释性评论:
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
visible: true
width: 200
height: 200
ListView {
anchors.fill: parent
model: ListModel {
ListElement {
name: "aaa"
}
ListElement {
name: "bbb"
}
ListElement {
name: "ccc"
}
}
delegate: TextEdit {
text: name
// In the delegate you can access the ListView via "ListView.view"
width: ListView.view.width
height: 50
activeFocusOnPress: false
// directly bind the property to two properties (also saving the brackets)
onActiveFocusChanged: font.italic = activeFocus
MouseArea {
anchors.fill: parent
onDoubleClicked : {
parent.forceActiveFocus(Qt.MouseFocusReason)
parent.ListView.view.currentIndex = index
}
}
}
}
}
考虑以下示例。
Rectangle {
height: 200
width: 200
ListView {
id: lv
anchors.fill: parent
model: ListModel {
ListElement {
name: "aaa"
}
ListElement {
name: "bbb"
}
ListElement {
name: "ccc"
}
}
delegate: TextEdit {
id: delegate
text: name
width: 200
height: 100
activeFocusOnPress: false
onActiveFocusChanged: {
if(activeFocus) {
font.italic = true;
} else {
font.italic = false;
}
}
MouseArea {
anchors.fill: parent
onDoubleClicked : {
delegate.focus = true;
lv.currentIndex = index;
}
}
}
}
}
我希望能够通过双击激活 TextEdit。如果它在列表视图之外,它会按预期工作,但在列表视图中它不起作用。 我猜问题是列表视图是焦点范围,但我不知道如何解决它。
提前致谢。
你可以利用 forceActiveFocus
:
This method sets focus on the item and ensures that all ancestor FocusScope objects in the object hierarchy are also given focus.
您可以使用重载版本(不带参数)或带有 FocusReason
的版本。这是使用后者的代码的修改版本。我还做了两个小调整,并附上解释性评论:
import QtQuick 2.4
import QtQuick.Window 2.2
Window {
visible: true
width: 200
height: 200
ListView {
anchors.fill: parent
model: ListModel {
ListElement {
name: "aaa"
}
ListElement {
name: "bbb"
}
ListElement {
name: "ccc"
}
}
delegate: TextEdit {
text: name
// In the delegate you can access the ListView via "ListView.view"
width: ListView.view.width
height: 50
activeFocusOnPress: false
// directly bind the property to two properties (also saving the brackets)
onActiveFocusChanged: font.italic = activeFocus
MouseArea {
anchors.fill: parent
onDoubleClicked : {
parent.forceActiveFocus(Qt.MouseFocusReason)
parent.ListView.view.currentIndex = index
}
}
}
}
}