【问题标题】:QML ListView current item not changing with keystrokes or mouseQML ListView当前项目不随击键或鼠标而改变
【发布时间】:2014-05-28 15:58:44
【问题描述】:

我有一个非常简单的 ListView。

ListView {
    id: logListView
    anchors.fill: parent
    model: LogEntryListModel

    delegate:
        Text {
        text: "Log Item: " + timestamp + ", " + verb
    }
    highlight: Rectangle { color: "lightsteelblue"; radius: 5 }
    focus: true
    clip: true
}

它可以很好地显示模型并突出显示第一项。当我单击另一个项目或使用箭头键时,它不会移动突出显示。我知道如何通过添加事件处理程序手动控制突出显示的项目,但我在文档中看到了对 selectedItem 自动处理的引用。我想知道:

QML 是否提供所选项目突出显示的自动更改?我需要添加什么才能打开它?

【问题讨论】:

    标签: qt qml


    【解决方案1】:

    键盘处理是自动完成的:

    import QtQuick 2.0
    import QtQuick.Controls 1.1
    
    Rectangle {
        width: 400
        height: 400
    
        ListView {
            id: logListView
            anchors.fill: parent
            model: 10
    
            delegate: Text {
                text: "Log Item: " + modelData
            }
            highlight: Rectangle { 
                color: "lightsteelblue"; 
                radius: 5
            }
            focus: true
            clip: true
        }
    }
    

    如果使用向上和向下箭头键不会为您更改所选项目,使用上面的代码,那么这是一个错误。

    但是,默认情况下不处理使用鼠标选择项目;只有轻弹/拖动列表。不过,它很容易添加:

    import QtQuick 2.0
    import QtQuick.Controls 1.1
    
    Rectangle {
        width: 400
        height: 400
    
        ListView {
            id: logListView
            anchors.fill: parent
            model: 10
    
            delegate: Text {
                text: "Log Item: " + modelData
    
                MouseArea {
                    anchors.fill: parent
                    onClicked: logListView.currentIndex = index
                }
            }
            highlight: Rectangle {
                color: "lightsteelblue";
                radius: 5
            }
            focus: true
            clip: true
        }
    }
    

    【讨论】:

    • 当我从头开始时,即使我将 ListView 分离到另一个 QML 文件中,您的示例也适用于我。在到达 ListView 之前,我必须有东西拦截击键。
    • 这已经很老了,但我遇到了和 Nathanial 一样的问题。也许这是新的,但类似情况的快速解决方案是forceActiveFocusonClicked: { logListView.currentIndex = index; logListView.forceActiveFocus(); } 为我工作
    猜你喜欢
    • 2016-12-08
    • 2021-04-02
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多