Search code examples
qtqpainterqimage

Why does my QPainter instance only draw when I use a specific .png?


I'm creating a simple "frogger" type game with Qt Creator. I managed to get a player that works with 4 directional keys, and a car that moves on its own across the screen. I have separate Player, Car, and Frogger class.

The Frogger class paints the images in paintEvent:

painter.drawImage(player->getRect(), player->getImage());
painter.drawImage(car->getRect(), car->getImage());

But I'm encountering a problem with trying to load a different image for the car. If I use image.load("player.png"); for both the car and the player constructors, I can see the car moving across the screen as a player image, and the player which moves according to my keys.

However if I replace the image with anything else (all images are in the same folder; I also tried adding it to Qt Creator under "Other files") such as "car.png," it doesn't seem to show up. I tried it with other images, but those don't show up for player either. Any ideas on why this might happen? I commented out my autoMove() function and nothing changes, so I don't think it's related to how I implement my move. Any ideas on what I might be missing?


Solution

  • I guess you can reduce the possible error locations to the procedure when you load the image. Try to confirm this by checking the return value of QImage::load:

    QString path = "player.png";
    bool loadSuccess = image.load(path);
    qDebug() << "Image" << path << "loaded? =>" << loadSuccess;
    

    If this will print false, check if Qt can find exactly the same path when just passing to QFile:

    if(!loadSuccess)
        qDebug() << "  File exists? =>" << QFile::exists(path);
    

    If this will print true, the image format can't be read by Qt. Possibly you use a non-standard PNG encoding. Are the images all from the same source? (Edited by the same image editor for example)

    However, if you still get the errors even when the first debug output above always prints true, the error is somewhere else. Then it could help to give us more code of how you use the images.