[英]QML: Gridview keyboard navigation not working
我正在使用gridview顯示從c ++端生成的復雜數據模型。 除了gridview不接受或響應任何keyNavigation事件之外,我一切正常。 這是我的代碼
GridView{
id: gridView
anchors.fill: parent
clip: true
cellWidth: 315
cellHeight: 300/6+15
focus: true
model: system.DataList
highlightFollowsCurrentItem: true
keyNavigationEnabled: true//enabled but still doesnt work
//keyNavigationWraps: true//does this matter
highlight: Rectangle{
color: highlightColor
radius: 5
width: gridView.cellWidth
height: gridView.cellHeight
x: gridView.currentItem.x
y: gridView.currentItem.y
Behavior on x { SpringAnimation { spring: 3; damping: 0.2 } }
Behavior on y { SpringAnimation { spring: 3; damping: 0.2 } }
}
delegate: Component{
Rectangle{
id: viewParentRect
width: gridView.cellWidth;
height: diskListView.cellHeight - 15
color: "transparent"
Row{
anchors.fill: parent
Rectangle{
width: parent.width/6 ; height: parent.height
color: "transparent"
Image {
id: image
anchors.centerIn: parent
source: model.modelData.IconPath
sourceSize.width: parent.width
sourceSize.height: parent.height
}
}
Column{
Text {
id: displayName
text: model.modelData.DisplayName
font.family: "Sans Serif"
font.pointSize: viewParentRect.width/30
}
Text {
id: usageText
text: model.modelData.Usage
font.family: "Sans Serif"
font.pointSize: viewParentRect.width/30
}
}
}
MouseArea{
anchors.fill: parent
onClicked: {
gridView.currentIndex = index
}
onDoubleClicked: {
system.enter(model.modelData.Path)
}
}
}
}
}
我嘗試將斷點保持在某些點,結果是,根本沒有觸發按鍵事件。 上面的代碼可以很好地與鼠標配合使用,但是由於我是為台式機開發的,因此我需要鍵盤導航才能正常工作(即使鼠標導航不起作用,這也不成問題)。
好吧,QML本身為GridView和ListView提供keyNavigation,只要它具有focus屬性設置為true且還具有用戶焦點即可。 如果其他組件是事后創建的,則焦點可能會被其他組件所竊取,這就是為什么鍵導航無法按預期工作的原因。
就我而言,我正在創建兩個具有兩個不同GridView的Component,然后將其與StackView作為父級,這從兩個GridView竊取了焦點。
我的第一個解決方法是通過StackView檢測keyPresses,如果它們是箭頭鍵和/或Enter / return鍵,則將它們傳遞給GridView。 將GridView的keyNavigationEnabled屬性設置為false並手動處理這些事件。 這種方法像冠軍一樣工作,但是代碼變得太復雜了。 所以我寫了第二種方法。
動態創建兩個組件,並在StackView中僅保留一個組件。 具有FocusScope的父GridView(以及其他需要排他焦點的項目),並通過父Component檢測焦點,並將其轉移給子組件。 最后,讓QML處理所有關鍵導航。 這是代碼,
main.qrc
StackView{
id: stackWindow
width: mainWindow.width
height: mainWindow.height
focus: true
Component.onCompleted: {push(Qt.createComponent("qrc:/PrimaryHomePage.qml"))}
onCurrentItemChanged: {currentItem.forceActiveFocus()}
Connections{
target: rSystem
ignoreUnknownSignals: true
onSwitchBetweenViews: {
if(newValue === 1){
stackWindow.pop()
stackWindow.push(Qt.createComponent("qrc:/SecondaryViewPage.qml"))
}
else if(newValue === 0){
stackWindow.pop()
stackWindow.push(Qt.createComponent("qrc:/PrimaryHomePage.qml"))
}
}
}
}
首先彈出,以確保StackView在一個項目中僅擁有一個項目(也可以使用替換)。
PrimaryHomePage.qrc
Item {
id: primaryHomePageParentItem
width: parent.width
height: parent.height
FocusScope{
id: focusScope
anchors.fill: parent
rGridView{
id: GridView_local
availablewidth: parent.width
}
}
onFocusChanged: {focusScope.focus = true}
}
幸運的是,它的工作速度比第一種方法還要快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.