Important: Please read the Qt Code of Conduct -

How to locate an image in a specific cell of a grid?

  • Hi, I'm trying to draw chess pieces in the right squares of a 8x8 grid created (obviously?) with the Grid element. I can't find the way to tell the image to be drawn in a specific square, though. There is the 'index' value that will be assigned to all cells from 0 to 63, but then I can't find out the syntax to define "cell 12 at chessboardGrid" as the parent of a specific piece.

    See the code that I'm using so far:

    @ Image {
    id: imageBoard
    source: "chessboard.svg" opponentZone.bottom
    width: parent.width
    fillMode: Image.PreserveAspectFit

    Grid {
        id: chessboardGrid
        columns: 8
        rows: 8
        anchors.fill: imageBoard
        Repeater {
            model: 64
            Rectangle {
                color: "transparent"
                border.width: 1 // only for testing, must be 0
                width: 60 // FIXME there must be a way not to hardcode this
                height: 60 // FIXME there must be a way not to hardcode this
        Image {
            id: whiteRook1
            source: "white/rook.svg"
            parent: chessboardGridFIXME // How to place this rook in a specific square

  • With Qt Quick 1.1 (which comes with Qt 4.8) you can call itemAt() on the Repeater object to get the item at a particular index.

    (In QtQuick 1.0 / Qt 4.7.x you can access the children of the Grid through Item::children() but this is not as straightforward because Repeater automatically adds other child objects, so the children() list may not always return what you expect.)

  • Hi blam, sorry for not answering before but I was trying to put my code together to explain my progress.

    Due to other reasons I decided to use ListModel + GridView instead. Locating items in a GridView was not evident either, but at least I could use a trick to manipulate the squares of the chess board that interested me:

    First a variable is defined:

    @Item { id: moveFrom; property Item pieceSelected }@

    Then whenever a specific delegate needs to be identified, the value is extracted and assigned to the variable:

    @moveFrom.pieceSelected = squareWrapper@

    You can find this code in its context "here": (lines 172 and 275).

    This allows to change properties of the specific delegate (e.g. from color blue to transparent - line 304).

    Still, a plain delegate id with a syntax like 'delegate.index' or similar would be nice. The previous tricks has limitations, like changing the state of a specific delegate. If someone know better ways I will be happy learning more about them.

Log in to reply