【问题标题】:QML skip item on ListView when using arrow keys使用箭头键时 QML 在 ListView 上跳过项目
【发布时间】:2015-09-29 10:11:54
【问题描述】:

我正在使用ListView,并希望在使用箭头键导航列表时跳过特定项目。

例如ListModel中有4个元素。

ListModel {
    id: myListModel
    ListElement {
        item_name: "Item 1"
        item_description: "Description 1"
    }
    ListElement {
        item_name: "Item 2"
        item_description: "Description 2"
    }
    ListElement {
        item_name: "Item 3"
        item_description: "Description 3"
    }
    ListElement {
        item_name: "Item 4"
        item_description: "Description 4"
    }
}

我希望在用户使用“向上”或“向下”键导航时始终跳过“第 3 项”。

例如,选择“项目4”并且用户按下“向上”键时,选择应从“第4项”跳转到“第2项”。同样,如果选择“项目 2”,然后按下“向下”键,则应选择“项目 4”(应跳过“项目 3”)

我在下面编写了委托,但它没有按我的预期运行:

// delegate
Component {
    id: myComponent
    Item {
        width: 40; height: 40
        enabled: (ListView.view.currentIndex === 2) false : true
        Text {
            anchors.centerIn: parent
            text: item_name
        }
    }
}

基本上,委托的enabled=false 没有按我的预期工作;任何帮助将不胜感激。

【问题讨论】:

  • 这个问题的四向部分是什么?例如,如果您使用向上和向下键一次导航 2 个项目,您如何向下移动 1 个项目?
  • 你已经写了评论,这些都是正确的方向。例如,只有“向上”和“向下”可用。

标签: listview qml


【解决方案1】:

您可能知道,具有键盘焦点的ListView 的默认行为是向上和向下导航一项。因此,您需要使用 Keys 的附加属性覆盖该行为:

import QtQuick 2.4
import QtQuick.Window 2.0

Window {
    width: 640
    height: 480
    visible: true

    ListModel {
        id: myListModel
        ListElement {
            item_name: "Item 1"
            item_description: "Description 1"
        }
        ListElement {
            item_name: "Item 2"
            item_description: "Description 2"
        }
        ListElement {
            item_name: "Item 3"
            item_description: "Description 3"
        }
        ListElement {
            item_name: "Item 4"
            item_description: "Description 4"
        }
    }

    ListView {
        id: listView
        width: 40
        height: 80
        focus: true
        anchors.centerIn: parent
        model: myListModel
        currentIndex: 0
        delegate: Item {
            id: delegateItem
            width: 40; height: 40
            Text {
                anchors.centerIn: parent
                text: item_name
                color: delegateItem.ListView.isCurrentItem ? "red" : "black"
            }
        }

        Keys.onDownPressed: {
            if (listView.currentIndex + 2 < listView.count - 1)
                listView.currentIndex += 2;
        }
        Keys.onUpPressed: {
            if (listView.currentIndex - 2 >= 0)
                listView.currentIndex -= 2;
        }
    }
}

您尚未指定用户一次应该如何导航一个项目,但您应该能够从上面的代码和Keys 的文档中弄清楚这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多