QML ListView默认无法点击高亮

ListView高亮的是当前选项(currentIndex),然而却没有处理按键、点击等事件,导致当前选项(currentIndex)没有及时更新。

如下示例代码:

 import QtQuick 2.0
 Rectangle{
     width: 120
     height : 300
     color : "white"
     ListView {
         id: listViewRoot
         anchors.fill : parent
         anchors.margins : 20
         clip : true
         model : 100
         delegate : numberDelegate
         spacing : 5
         focus : true
     }
     Component {
         id: numberDelegate
         Rectangle {
             width: ListView.view.width
             height : 40
             color : ListView.isCurrentItem ? "gray" : "lightGray"
             Text {
                 anchors.centerIn: parent
                 font.pixelSize : 10
                 text : index
             }              
         }
     }
 }

需要在numberDelegate里增加MouseArea,关键代码是listViewRoot.currentIndex = index,修改后的部分代码如下:

 Component {
         id: numberDelegate
         Rectangle {
             width: ListView.view.width
             height : 40
             color : ListView.isCurrentItem ? "gray" : "lightGray"
             Text {
                 anchors.centerIn: parent
                 font.pixelSize : 10
                 text : index
             }
             
             MouseArea {
                 anchors.fill: parent
                 onClicked: {
                     listViewRoot.currentIndex = index
                  }
             }
         }
     }

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注