Search code examples
qtdictionarytile

Draw 32x32 Tiled Images in QT


I'm curious to learn how to split an image into 32x32 (or really any size) selectable tiles and display them in Qt? An example is the Tiled Map Editor (the panel in the lower right corner of the screen). I'm thinking of trying to create a 2D level editor in Qt for fun but I'm fairly new to Qt and have yet to find the answer to this specific question. Or maybe I just don't know how to phrase the question.


Solution

  • Add your main image to a QPixmap, then for each tile that you want to create, call the QPixmap's copy function. This allows you to specify the area that you want to copy and returns you a new QPixmap with that area.

    With each QPixmap tile you create using copy, use this to create a QGraphicsPixmapItem, which you then add to the QGraphicsScene.

    So, you'd do something like this: -

    // assuming your source image is in your resources qrc file
    QPixmap srcImage(":/images/srcImage.png");
    
    //in a loop for x and a 2nd loop for y
    
    // copy a section of the source image
    QPixmap tileImg = srcImage.copy(x, y, w, h);
    
    // create the tile
    QGraphicsPixmapItem* pTile = new QGraphicsPixmapItem(tileImg);
    
    // add the pTile to the scene.
    

    Using QGraphicsPixmapItem will provide you with a tiled object that can be positioned in the scene, selected and moved about.