Important: Please read the Qt Code of Conduct -

Pixmap resize

  • I am looking to use QPixmap in a double-buffering application and I need to resize it when my widget is resized; however, there is not resize member function. I have code that works where I delete the Pixmap and create a new one with the new size. The documentary and online commentary seem to indicate the the preferred method of allocating the QPixmap is using the statement "QPixmap name" and not "QPixmap name = new QPixmap (qrect)". The latter is easy to resize, but the second is not. If I use the former to create data member, the how do I resize it? (This is probably a simple C++ question, but my C++ is very rusty.)

  • @ofmrew
    have you tried QPixmap::scaled?
    read Pixmap Transformations for more information

  • Lifetime Qt Champion

    @ofmrew Since QPixmap has a move assignment operator ( you can do:

    QPixmap pixmap;
    pixmap = pixmap.scaled(...);

  • Thanks to both, you got me thinking. Since the Pixmap will be used in an off-screen buffering operation and the aspect ratio will most likely be changed by the parent window being resized, the Pixmap should be redrawn, so scaling the old contents is inefficient. It look like

         pixmap = QPixmap(this->rect());

    is my best bet.

    Here, however, is a C++ question: If I define my pixmap to be a data member of a custom widget class using the statement "QPixmap pixmap" and then create a new Pixmap, where will the new one reside and what is its lifetime--I want it to last as long as my custom widget exists? Also, is the old one deleted or do I have a memory leak? (I told you my C++ is rusty.)

  • Lifetime Qt Champion


    It will be replaced.

  • @ofmrew
    I think

    pixmap = QPixmap( this->rect() );

    is the same as

    pixmap = pixmap.scaled( this->rect() );

    except that the first one doesn't have any content

    as for the life time, both way just construct a temporary object, and it will be destructed after the assignment. since their data will be assigned to pixmap so it's fine that the temporary object being destructed.

    and as @SGaist said, the old data in pixmap will be replaced

  • Thanks

    I got it to work.

Log in to reply