How can a GridView Element determine its index?

  • I need elements to determine if they are first or last. I can get GridView.view.count in the delegate but I can not determine what the element's index is in the list. I am on Qt 4.7.

  • you can maybe use a simple comparison if there is no attached index property?
    var first = grid.children[0] === delegate
    grid is the GridView id and delegate the id of the delegate ( i don't think you can use "this" :P )
    you might need to use grid.contentItem.children instead of grid.children i am not sure but many view container items in QML put the children in the contentItem and not the view directly (just loop though it or print the length).

    anyway my knowledge is that all view containers have an attached "index" property? I didn't try it with the GridView though.

    you may also try the int indexAt(int x, int y) function of the GridView, providing it with the position of the current delegate, but I don't know how well that works.

  • I was using mapToItem() and indexAt() which seems pretty inefficient.

    var o = mapToItem(GridView.view, 0, 0);
    var i = GridView.view.indexAt(o.x, o.y)

  • Ok to confirm this I just created a test project and GriedView works very well with the index property, so I don't know why it isn't working for you??

    My complete main.qml
    import QtQuick 2.0

    GridView {
    width: 360
    height: 360
    model: 8
    delegate: Text { text: index }

    maybe you always tried to access the index with the GriedView property? it is just "index" or in my example "modelData" to access the item of the model (with an int model it is the same as index).

  • This seems to work:

    var istop = GridView.view.children[0].children[0] != me;
    var isbottom = GridView.view.children[0].children[GridView.view.count -1] != me;

    I'm not clear why I need the children[0].children[] but at least it seems to work.

  • did you check my last post? also I did tell you before why you need to get children[0] or better contentItem. that is a design of the QML views they don't hold their delegate children directly, but in the contentItem child!

    so with my last example above if you print this:
    Component.onCompleted: console.log(children.length, contentItem.children.length)
    the output is "1 9", so the 9 children are in the contentItem! but you should be able to just use index instead of contentItem.children[0] etc.?

  • This what I ended up with:

    var istop = return GridView.view.contentItem.children[0] != me;
    var isbottom = return GridView.view.contentItem.children[GridView.view.count -1] != me

    me is the id of my component. This and delegate didn't work.

    Thanks for the help.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.