Search code examples
c++qtqpixmap

C++ Qt QPixmap load always returns false


I try to load an image using QPixmap.

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QPixmap test;
    qDebug()<< test.load(":/test.bmp");
}

No matter how I change the file path, it always returns false. What's wrong?


Solution

  • TL;DR: Add following line to your .pro file.

    RESOURCES += test.bmp
    

    File paths that start with a colon like the ":/test.bmp" above are treated like resources (see http://doc.qt.io/qt-5/resources.html) and are compiled into the binary, so you don't need to ship them as files (I would only use a resource if the BMP file is not that big, because it will be in memory when the binary is loaded).

    Alternatively, you could just give the relative or absolute path to your file in QPixmap::load() without the colon, e.g. test.load("test.bmp").