2015-03-31 83 views
1

請考慮以下示例。將焦點強制爲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。如果它在列表視圖之外,它按預期工作,但在列表視圖中它不起作用。 我想問題是列表視圖是焦點範圍,但我不知道如何解決它。

在此先感謝。

回答

1

您可以利用forceActiveFocus

此方法將重點放在項目和確保所有祖先FocusScope對象層次對象也給予重點

您可以使用重載版本(不帶參數)或帶有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 
       } 
      } 
     } 
    } 
} 
+1

謝謝,它的工作 – 2015-04-01 15:28:20