Search code examples
c++qtnullqt5qpixmap

How to set QPixmap to null


I have a function that receives reference to QPixmap as a parameter like so:

void myFunction(QPixmap &pixmap){
    //[...]
}

How can I set the pixmap to "null" so that pixmap.isNull() returns true after calling myFunction() on a pixmap that had loaded content in it?

Example:

//1. Create pixmap
QPixmap pixmap;
qDebug() << pixmap.isNull(); //true

//2. load image
pixmap.load("existing_image.png");
qDebug() << pixmap.isNull(); //false

//3. run myFunction on pixmap
myFunction(pixmap);
qDebug() << pixmap.isNull(); //true

Solution

  • One way would be to use the swap() method to replace the image data with a null QPixmap:

    void myFunction(QPixmap &pixmap){
        pixmap.swap(QPixmap());
    }
    

    The documentation for swap() (linked above) states:

    Swaps pixmap other with this pixmap. This operation is very fast and never fails.