2016-09-20 55 views
1

我有一個StackView,其中有兩個項目。這兩個項目都應該處理一些鍵。StackView中的多項關鍵處理

我會假設,如果StackView中的currentItem不處理密鑰,密鑰將被轉發到較低層,但顯然情況並非如此。

以下示例說明了此問題。當按例如'A'時,我看到鑰匙由​​和堆棧視圖本身處理,但鑰匙不由layer0處理。

注意layer0由於transitionFinished

import QtQuick 2.0 
import QtQuick.Window 2.2 
import QtQuick.Controls 1.4 

Window { 
    id: mainWindow 
    visible: true 
    width: 1280 
    height: 720 
    color: "black" 

    Component { 
     id: layer0 
     Rectangle { 
      focus:true 
      width:200;height:200;color:"red" 
      Keys.onPressed: console.log("layer0") 
     } 
    } 
    Component { 
     id: layer1 
     Rectangle { 
      focus:true 
      width:200;height:200;color:"#8000FF00" 
      Keys.onPressed: console.log("layer1") 
     } 
    } 

    StackView { 
     id: stack 
     width: parent.width 
     height: parent.height 
     focus: true 

     Component.onCompleted: { 
      stack.push(layer0) 
      stack.push(layer1).focus=true 
     } 

     Keys.onPressed: { 
      console.log("StackView.onPressed") 
     } 

     delegate: StackViewDelegate { 
      function transitionFinished(properties) 
      { 
       properties.exitItem.visible = true 
       properties.exitItem.focus = true 
      } 
     } 
    } 
} 

回答

2

properties.exitItem.visible = true發言中,我會假設,如果在StackView的CURRENTITEM不處理的關鍵仍然是在它的上面推​​後可見,這密鑰將被轉發到較低層,但顯然情況並非如此。

顯然根據Qt Documentation鍵事件傳播是這樣的:

如果與活性焦點的QQuickItem接受的按鍵事件,傳播停止。否則,事件被髮送到項目的父項,直到事件被接受,或者到達根項目。

如果我理解正確,在你的例子中,兩個項目是兄弟姐妹。 Layer1具有焦點,它將在層次結構中傳播事件UP,而不是水平或向下。此外,這些多個focus: true不會有任何影響,因爲最後一個項目接收焦點將得到它,在這種情況下,層1中Component.onCompleted

一種方式來解決,這可能是定義一個新的信號,也就是說,

Window { 
    id: mainWindow 
    ... 
    signal keyReceived(int key) 

,然後在StackView火上Keys.onPressed該事件:

Keys.onPressed: { 
     console.log("StackView.onPressed") 
     keyReceived(event.key) 
    } 

最後抓住你的矩形新的信號:

Component { 
    id: layer1 
    Rectangle { 
     Connections { 
      target: mainWindow 
      onKeyReceived: console.log("layer1") 
     } 
    } 
} 
+0

感謝您的解釋(特別是父母vs兄弟姐妹部分)! 您的建議有兩個缺點:我們無法阻止傳播(雖然我們可以檢查event.accepted標誌),但我們不能保證(我認爲)密鑰最先被最高層接收。 我將看看Keys.forwardTo(lowerLayerItem)方法。 –