2015-03-31 85 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