2

I creating simple image viewer for education purpose. I have class ScreenImage which including QPixMap for load image. For load image from drive I use QPixMap::load().

class ScreenImage : public QWidget
{
    Q_OBJECT

    public:
          ...

    bool loadImage(const QString &filename);


    QScrollArea *_pScrollArea;
    QLabel *_pLabel;
    QPixmap *_pPixmap;

    ...
};

The question: how to delete already loaded into QPixMap image? And if I loaded new image in the same QPixMap then memory for previously loaded image will lost? (will memory leak)?

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142

2 Answers2

2

You don't need to allocate a QPixmap on the heap. Think of QPixmap as an int. Would you use a pointer to int in your class?

Hence:

class MyWidget : public QWidget {
     QPixmap m_pixmap;
public:
     void loadFile(const QString &path) {
           m_pixmap.load(path);
     }
};

is correct and doesn't leak anything.

peppe
  • 21,934
  • 4
  • 55
  • 70
1

First, I recommend using QImage. QImage uses implicit sharing of memory, so you don't have to new or deep copy the image when using it. To de-allocate the QImage, simply assign it to an empty image:

QImage img;
...
img = QImage();

For further understanding I suggest reading about the difference between QImage & QPixmap. The short of it is: don't use QPixmap outside of the gui thread.

Community
  • 1
  • 1
Klathzazt
  • 2,415
  • 19
  • 27