QML如何在ListView中获取当前元素索引?

时间:2014-12-16 19:41:59

标签: qt listview qml qt5 qtquick2

例如:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2

ApplicationWindow {
    width: 250
    height: 250
    visible: true

    Rectangle {
        anchors.fill: parent

        ListModel {
            id: colorsModel
            ListElement { colorCode: "red"   }
            ListElement { colorCode: "green" }
            ListElement { colorCode: "blue"  }
            ListElement { colorCode: "orange"}
        }

        ListView {
            anchors.fill: parent
            snapMode: ListView.SnapOneItem
            model: colorsModel

            delegate: Rectangle {
                width: 250
                height: 250
                color: colorCode
            }

            onMovementEnded: {
                console.log($CurrentElementIndex$)
            }
        }
    }
}

如何将当前元素索引获取到$ CurrentElementIndex $占位符?

ListView.currentIndex只是write属性,就像我理解正确一样。

也许我可以使用ListView.indexAt(),但我不明白它是如何工作的。

3 个答案:

答案 0 :(得分:2)

列表完成滚动后,将调用

onMovementEnded()。这与项目选择无关。您可以添加一个荧光笔来调试当前选择的元素并使用onCurrentIndexChanged处理程序:

ListView {
    anchors.fill: parent
    snapMode: ListView.SnapOneItem
    model: colorsModel

    delegate: Rectangle {
        width: 250
        height: 250
        color: colorCode
    }

    highlight: Rectangle {
        anchors.fill: parent
        color: "red"
    }

    onCurrentIndexChanged: console.log(currentIndex)

    // ...

答案 1 :(得分:2)

您可以使用currentIndex来获取和设置当前所选项目。 但你说:

  

我希望它在滚动期间获得新索引

因此您需要在ListView中设置highlightRangeMode: ListView.StrictlyEnforceRange。每当您滚动列表时,这将更改currentIndex属性 这是一些例子:

ListView {
    id: list
    anchors.fill: parent
    model: 10
    orientation: ListView.Vertical
    snapMode: ListView.SnapOneItem
    highlightRangeMode: ListView.StrictlyEnforceRange     //<--This is the key note
    header: Component { Item { width: 1; height: 30 } }
    footer: Component { Item { width: 1; height: 30 } }
    preferredHighlightBegin: height/2-10    //<-----using these two lines you can control position of the selected item
    preferredHighlightEnd: height/2-10      //<--|
    currentIndex: 3
    onCurrentIndexChanged: {
        console.log("current selected index is: "+currentIndex);    //<-- Test output
    }

    delegate: Component {
        Text {
            id: _root
            width: parent.width
            height: 20
            horizontalAlignment: Text.AlignHCenter
            color: "#888"
            font { family: "Segoe UI Light"; pixelSize: 18 }
            text: index
        }
    }
}

有关更多信息,请参阅Qt。

的文件

答案 2 :(得分:0)

FROM php:7.2-fpm 
RUN apt-get update
RUN apt-get install libzip-dev -y
RUN docker-php-ext-configure zip --with-libzip \
  && docker-php-ext-install zip