Home · All Classes · Modules

QPixmap Class Reference
[QtGui module]

The QPixmap class is an off-screen image representation that can be used as a paint device. More...

Inherits QPaintDevice.

Inherited by QBitmap.

Methods

Static Methods


Detailed Description

The QPixmap class is an off-screen image representation that can be used as a paint device.

Qt provides four classes for handling image data: QImage, QPixmap, QBitmap and QPicture. QImage is designed and optimized for I/O, and for direct pixel access and manipulation, while QPixmap is designed and optimized for showing images on screen. QBitmap is only a convenience class that inherits QPixmap, ensuring a depth of 1. The isQBitmap() function returns true if a QPixmap object is really a bitmap, otherwise returns false. Finally, the QPicture class is a paint device that records and replays QPainter commands.

A QPixmap can easily be displayed on the screen using QLabel or one of QAbstractButton's subclasses (such as QPushButton and QToolButton). QLabel has a pixmap property, whereas QAbstractButton has an icon property. And because QPixmap is a QPaintDevice subclass, QPainter can be used to draw directly onto pixmaps.

In addition to the ordinary constructors, a QPixmap can be constructed using the static grabWidget() and grabWindow() functions which creates a QPixmap and paints the given widget, or window, in it.

Note that the pixel data in a pixmap is internal and is managed by the underlying window system. Pixels can only be accessed through QPainter functions or by converting the QPixmap to a QImage. Depending on the system, QPixmap is stored using a RGB32 or a premultiplied alpha format. If the image has an alpha channel, and if the system allows, the preferred format is premultiplied alpha. Note also that QPixmap, unlike QImage, may be hardware dependent. On X11 and Mac, a QPixmap is stored on the server side while a QImage is stored on the client side (on Windows, these two classes have an equivalent internal representation, i.e. both QImage and QPixmap are stored on the client side and don't use any GDI resources).

There are functions to convert between QImage and QPixmap. Typically, the QImage class is used to load an image file, optionally manipulating the image data, before the QImage object is converted into a QPixmap to be shown on screen. Alternatively, if no manipulation is desired, the image file can be loaded directly into a QPixmap. On Windows, the QPixmap class also supports conversion between HBITMAP and QPixmap.

QPixmap provides a collection of functions that can be used to obtain a variety of information about the pixmap. In addition, there are several functions that enables transformation of the pixmap.

QPixmap objects can be passed around by value since the QPixmap class uses implicit data sharing. For more information, see the Implicit Data Sharing documentation. QPixmap objects can also be streamed.

Reading and Writing Image Files

QPixmap provides several ways of reading an image file: The file can be loaded when constructing the QPixmap object, or by using the load() or loadFromData() functions later on. When loading an image, the file name can either refer to an actual file on disk or to one of the application's embedded resources. See The Qt Resource System overview for details on how to embed images and other resource files in the application's executable.

Simply call the save() function to save a QPixmap object.

The complete list of supported file formats are available through the QImageReader.supportedImageFormats() and QImageWriter.supportedImageFormats() functions. New file formats can be added as plugins. By default, Qt supports the following formats:

Format Description Qt's support
BMP Windows Bitmap Read/write
GIF Graphic Interchange Format (optional) Read
JPG Joint Photographic Experts Group Read/write
JPEG Joint Photographic Experts Group Read/write
PNG Portable Network Graphics Read/write
PBM Portable Bitmap Read
PGM Portable Graymap Read
PPM Portable Pixmap Read/write
XBM X11 Bitmap Read/write
XPM X11 Pixmap Read/write


(To configure Qt with GIF support, pass -qt-gif to the configure script or check the appropriate option in the graphical installer.)

Pixmap Information

QPixmap provides a collection of functions that can be used to obtain a variety of information about the pixmap:

Available Functions
Geometry The size(), width() and height() functions provide information about the pixmap's size. The rect() function returns the image's enclosing rectangle.
Alpha component The hasAlphaChannel() returns true if the pixmap has a format that respects the alpha channel, otherwise returns false, while the hasAlpha() function returns true if the pixmap has an alpha channel or a mask (otherwise false).

The alphaChannel() function returns the alpha channel as a new QPixmap object, while the mask() function returns the mask as a QBitmap object. The alpha channel and mask can be set using the setAlphaChannel() and setMask() functions, respectively.

Low-level information The depth() function returns the depth of the pixmap. The defaultDepth() function returns the default depth, i.e. the depth used by the application on the given screen.

The serialNumber() function returns a number that uniquely identifies the contents of the QPixmap object.

The x11Info() function returns information about the configuration of the X display used to display the widget. The x11PictureHandle() function returns the X11 Picture handle of the pixmap for XRender support. Note that the two latter functions are only available on x11.



Pixmap Conversion

A QPixmap object can be converted into a QImage using the toImage() function. Likewise, a QImage can be converted into a QPixmap using the fromImage(). If this is too expensive an operation, you can use QBitmap.fromImage() instead.

In addition, on Windows, the QPixmap class supports conversion to and from HBitmap: the toWinHBITMAP() function creates a HBITMAP equivalent to the QPixmap, based on the given HBitmapFormat, and returns the HBITMAP handle. The fromWinHBITMAP() function returns a QPixmap that is equivalent to the given bitmap which has the specified format.

Pixmap Transformations

QPixmap supports a number of functions for creating a new pixmap that is a transformed version of the original: The createHeuristicMask() function creates and returns a 1-bpp heuristic mask (i.e. a QBitmap) for this pixmap. It works by selecting a color from one of the corners and then chipping away pixels of that color, starting at all the edges. The createMaskFromColor() function creates and returns a mask (i.e. a QBitmap) for the pixmap based on a given color.

The scaled(), scaledToWidth() and scaledToHeight() functions return scaled copies of the pixmap, while the copy() function creates a QPixmap that is a plain copy of the original one.

The transformed() function returns a copy of the pixmap that is transformed with the given transformation matrix and transformation mode: Internally, the transformation matrix is adjusted to compensate for unwanted translation, i.e. transformed() returns the smallest pixmap containing all transformed points of the original pixmap. The static trueMatrix() function returns the actual matrix used for transforming the pixmap.

There are also functions for changing attributes of a pixmap. in-place: The fill() function fills the entire image with the given color, the setMask() function sets a mask bitmap, and the setAlphaChannel() function sets the pixmap's alpha channel.

See also QBitmap, QImage, QImageReader, and QImageWriter.


Method Documentation

QPixmap.__init__ (self)

Constructs a null pixmap.

See also isNull().

QPixmap.__init__ (self, int w, int h)

Constructs a pixmap with the given width and height.

The content of the pixmap is uninitialized. If either width or height is zero, a null pixmap is constructed.

See also isNull().

QPixmap.__init__ (self, QSize)

Constructs a pixmap from the file with the given fileName. If the file does not exist or is of an unknown format, the pixmap becomes a null pixmap.

The loader attempts to read the pixmap using the specified format. If the format is not specified (which is the default), the loader probes the file for a header to guess the file format.

The file name can either refer to an actual file on disk or to one of the application's embedded resources. See the Resource System overview for details on how to embed images and other resource files in the application's executable.

If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the flags to control the conversion.

The fileName, format and flags parameters are passed on to load(). This means that the data in fileName is not compiled into the binary. If fileName contains a relative path (e.g. the filename only) the relevant file must be found relative to the runtime working directory.

See also Reading and Writing Image Files.

QPixmap.__init__ (self, QString fileName, str format = None, Qt.ImageConversionFlags flags = Qt.AutoColor)

Constructs a pixmap from the given xpm data, which must be a valid XPM image.

Errors are silently ignored.

Note that it's possible to squeeze the XPM variable a little bit by using an unusual declaration:

 static const char * const start_xpm[]={
     "16 15 8 1",
     "a c #cec6bd",
 ....

The extra const makes the entire definition read-only, which is slightly more efficient (for example, when the code is in a shared library) and ROMable when the application is to be stored in ROM.

QPixmap.__init__ (self, list xpm)

Constructs a pixmap that is a copy of the given pixmap.

See also copy().

QPixmap.__init__ (self, QPixmap)

Use the constructor that takes a Qt.ImageConversionFlag instead.

QPixmap.__init__ (self, QVariant variant)

Constructs a pixmap from the QImage image.

Use the static fromImage() function instead.

QPixmap QPixmap.alphaChannel (self)

Returns the alpha channel of the pixmap as a new grayscale QPixmap in which each pixel's red, green, and blue values are given the alpha value of the original pixmap. The color depth of the returned pixmap is the system depth on X11 and 8-bit on Windows and Mac OS X.

You can use this function while debugging to get a visible image of the alpha channel. If the pixmap doesn't have an alpha channel, i.e., the alpha channel's value for all pixels equals 0xff), a null pixmap is returned. You can check this with the isNull() function.

We show an example:

[Missing image alphachannelimage.png]

See also setAlphaChannel() and Pixmap Information.

QPixmap QPixmap.copy (self, QRect rect = QRect())

Returns a deep copy of the subset of the pixmap that is specified by the given rectangle. For more information on deep copies, see the Implicit Data Sharing documentation.

If the given rectangle is empty, the whole image is copied.

See also operator=(), QPixmap(), and Pixmap Transformations.

QPixmap QPixmap.copy (self, int ax, int ay, int awidth, int aheight)

This is an overloaded member function, provided for convenience.

Returns a deep copy of the subset of the pixmap that is specified by the rectangle QRect( x, y, width, height).

QBitmap QPixmap.createHeuristicMask (self, bool clipTight = True)

Creates and returns a heuristic mask for this pixmap.

The function works by selecting a color from one of the corners and then chipping away pixels of that color, starting at all the edges. If clipTight is true (the default) the mask is just large enough to cover the pixels; otherwise, the mask is larger than the data pixels.

The mask may not be perfect but it should be reasonable, so you can do things such as the following:

 QPixmap myPixmap;
 myPixmap->setMask(myPixmap->createHeuristicMask());

This function is slow because it involves transformation to a QImage, non-trivial computations and a transformation back to a QBitmap.

See also QImage.createHeuristicMask() and Pixmap Transformations.

QBitmap QPixmap.createMaskFromColor (self, QColor maskColor)

Creates and returns a mask for this pixmap based on the given maskColor.

This function is slow because it involves transformation to a QImage and a transformation back to a QBitmap.

See also createHeuristicMask() and Pixmap Transformations.

int QPixmap.defaultDepth ()

Returns the default pixmap depth used by the application.

See also depth() and Pixmap Information.

int QPixmap.depth (self)

Returns the depth of the pixmap.

The pixmap depth is also called bits per pixel (bpp) or bit planes of a pixmap. A null pixmap has depth 0.

See also defaultDepth() and Pixmap Information.

QPixmap.detach (self)

Detaches the pixmap from shared pixmap data.

A pixmap is automatically detached by Qt whenever its contents are about to change. This is done in almost all QPixmap member functions that modify the pixmap (fill(), fromImage(), load(), etc.), and in QPainter.begin() on a pixmap.

There are two exceptions in which detach() must be called explicitly, that is when calling the handle() or the x11PictureHandle() function (only available on X11). Otherwise, any modifications done using system calls, will be performed on the shared data.

The detach() function returns immediately if there is just a single reference or if the pixmap has not been initialized yet.

int QPixmap.devType (self)

QPixmap.fill (self, QColor fillColor = Qt.white)

Fills the pixmap with the given fillColor.

See also Pixmap Transformations.

QPixmap.fill (self, QWidget widget, QPoint ofs)

This is an overloaded member function, provided for convenience.

Fills the pixmap with the widget's background color or pixmap according to the given offset.

The QPoint offset defines a point in widget coordinates to which the pixmap's top-left pixel will be mapped to. This is only significant if the widget has a background pixmap; otherwise the pixmap will simply be filled with the background color of the widget.

QPixmap.fill (self, QWidget widget, int xofs, int yofs)

This is an overloaded member function, provided for convenience.

Fills the pixmap with the widget's background color or pixmap. The given point, (x, y), defines an offset in widget coordinates to which the pixmap's top-left pixel will be mapped to.

QPixmap QPixmap.fromImage (QImage image, Qt.ImageConversionFlags flags = Qt.AutoColor)

Converts the given image to a pixmap using the specified flags to control the conversion. The flags argument is a bitwise-OR of the Qt.ImageConversionFlags. Passing 0 for flags sets all the default options.

In case of monochrome and 8-bit images, the image is first converted to a 32-bit pixmap and then filled with the colors in the color table. If this is too expensive an operation, you can use QBitmap.fromImage() instead.

See also toImage() and Pixmap Conversion.

QPixmap QPixmap.grabWidget (QWidget widget, QRect rect)

Creates a pixmap and paints the given widget, restricted by the given rectangle, in it. If the widget has any children, then they are also painted in the appropriate positions.

If no rectangle is specified (the default) the entire widget is painted.

If widget is 0, the specified rectangle doesn't overlap the widget's rectangle, or an error occurs, the function will return a null QPixmap. If the rectangle is a superset of the given widget, the areas outside the widget are covered with the widget's background.

This function actually asks widget to paint itself (and its children to paint themselves) by calling paintEvent() with painter redirection turned on. But QPixmap also provides the grabWindow() function which is a bit faster grabbing pixels directly off the screen. In addition, if there are overlaying windows, grabWindow(), unlike grabWidget(), will see them.

Warning: Do not call this function from QWidget.paintEvent().

See also grabWindow().

QPixmap QPixmap.grabWidget (QWidget widget, int x = 0, int y = 0, int w = -1, int h = -1)

This is an overloaded member function, provided for convenience.

Creates a pixmap and paints the given widget, restricted by QRect(x, y, width, height), in it.

Warning: Do not call this function from QWidget.paintEvent().

QPixmap QPixmap.grabWindow (unsigned long, int x = 0, int y = 0, int w = -1, int h = -1)

Creates and returns a pixmap constructed by grabbing the contents of the given window restricted by QRect(x, y, width, height).

The arguments (x, y) specify the offset in the window, whereas (width, height) specify the area to be copied. If width is negative, the function copies everything to the right border of the window. If height is negative, the function copies everything to the bottom of the window.

The window system identifier (WId) can be retrieved using the QWidget.winId() function. The rationale for using a window identifier and not a QWidget, is to enable grabbing of windows that are not part of the application, window system frames, and so on.

The grabWindow() function grabs pixels from the screen, not from the window, i.e. if there is another window partially or entirely over the one you grab, you get pixels from the overlying window, too. The mouse cursor is generally not grabbed.

Note on X11that if the given window doesn't have the same depth as the root window, and another window partially or entirely obscures the one you grab, you will not get pixels from the overlying window. The contents of the obscured areas in the pixmap will be undefined and uninitialized.

Warning: In general, grabbing an area outside the screen is not safe. This depends on the underlying window system.

See also grabWidget() and Screenshot Example.

unsigned long QPixmap.handle (self)

Returns the pixmap's handle to the device context.

Note that, since QPixmap make use of implicit data sharing, the detach() function must be called explicitly to ensure that only this pixmap's data is modified if the pixmap data is shared.

Warning: This function is X11 specific; using it is non-portable.

See also detach().

bool QPixmap.hasAlpha (self)

Returns true if this pixmap has an alpha channel, or has a mask, otherwise returns false.

See also hasAlphaChannel(), alphaChannel(), and mask().

bool QPixmap.hasAlphaChannel (self)

Returns true if the pixmap has a format that respects the alpha channel, otherwise returns false.

See also alphaChannel() and hasAlpha().

int QPixmap.height (self)

Returns the height of the pixmap.

See also size() and Pixmap Information.

bool QPixmap.isDetached (self)

bool QPixmap.isNull (self)

Returns true if this is a null pixmap; otherwise returns false.

A null pixmap has zero width, zero height and no contents. You cannot draw in a null pixmap.

bool QPixmap.isQBitmap (self)

Returns true if this is a QBitmap; otherwise returns false.

bool QPixmap.load (self, QString fileName, str format = None, Qt.ImageConversionFlags flags = Qt.AutoColor)

Loads a pixmap from the file with the given fileName. Returns true if the pixmap was successfully loaded; otherwise returns false.

The loader attempts to read the pixmap using the specified format. If the format is not specified (which is the default), the loader probes the file for a header to guess the file format.

The file name can either refer to an actual file on disk or to one of the application's embedded resources. See the Resource System overview for details on how to embed pixmaps and other resource files in the application's executable.

If the data needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the flags to control the conversion.

See also loadFromData() and Reading and Writing Image Files.

bool QPixmap.loadFromData (self, str buf, str format = None, Qt.ImageConversionFlags flags = Qt.AutoColor)

Loads a pixmap from the len first bytes of the given binary data. Returns true if the pixmap was loaded successfully; otherwise returns false.

The loader attempts to read the pixmap using the specified format. If the format is not specified (which is the default), the loader probes the file for a header to guess the file format.

If the data needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the flags to control the conversion.

See also load() and Reading and Writing Image Files.

bool QPixmap.loadFromData (self, QByteArray buf, str format = None, Qt.ImageConversionFlags flags = Qt.AutoColor)

This is an overloaded member function, provided for convenience.

Use the loadFromData() function that takes a Qt.ImageConversionFlag instead.

QBitmap QPixmap.mask (self)

Returns the mask, or a null bitmap if no mask has been set.

See also setMask() and Pixmap Information.

int QPixmap.metric (self, QPaintDevice.PaintDeviceMetric)

QPaintEngine QPixmap.paintEngine (self)

QRect QPixmap.rect (self)

Returns the pixmap's enclosing rectangle.

See also Pixmap Information.

bool QPixmap.save (self, QString fileName, str format = None, int quality = -1)

Saves the pixmap to the file with the given fileName using the specified image file format and quality factor. Returns true if successful; otherwise returns false.

The quality factor must be in the range [0,100] or -1. Specify 0 to obtain small compressed files, 100 for large uncompressed files, and -1 to use the default settings.

If format is 0, an image format will be chosen from fileName's suffix.

See also Reading and Writing Image Files.

bool QPixmap.save (self, QIODevice device, str format = None, int quality = -1)

This is an overloaded member function, provided for convenience.

This function writes a QPixmap to the given device using the specified image file format and quality factor. This can be used, for example, to save a pixmap directly into a QByteArray:

         QPixmap pixmap;
         QByteArray bytes;
         QBuffer buffer(&bytes);
         buffer.open(QIODevice.WriteOnly);
         pixmap.save(&buffer, "PNG"); // writes pixmap into bytes in PNG format

QPixmap QPixmap.scaled (self, int w, int h, Qt.AspectRatioMode aspectMode = Qt.IgnoreAspectRatio, Qt.TransformationMode mode = Qt.FastTransformation)

Scales the pixmap to the given size, using the aspect ratio and transformation modes specified by aspectRatioMode and transformMode.

If the given size is empty, this function returns a null pixmap.

See also isNull() and Pixmap Transformations.

QPixmap QPixmap.scaled (self, QSize s, Qt.AspectRatioMode aspectMode = Qt.IgnoreAspectRatio, Qt.TransformationMode mode = Qt.FastTransformation)

This is an overloaded member function, provided for convenience.

Returns a copy of the pixmap scaled to a rectangle with the given width and height according to the given aspectRatioMode and transformMode.

If either the width or the height is zero or negative, this function returns a null pixmap.

QPixmap QPixmap.scaledToHeight (self, int h, Qt.TransformationMode mode = Qt.FastTransformation)

Returns a scaled copy of the image. The returned image is scaled to the given height using the specified transformation mode. The width of the pixmap is automatically calculated so that the aspect ratio of the pixmap is preserved.

If height is 0 or negative, a null pixmap is returned.

See also isNull() and Pixmap Transformations.

QPixmap QPixmap.scaledToWidth (self, int w, Qt.TransformationMode mode = Qt.FastTransformation)

Returns a scaled copy of the image. The returned image is scaled to the given width using the specified transformation mode. The height of the pixmap is automatically calculated so that the aspect ratio of the pixmap is preserved.

If width is 0 or negative, a null pixmap is returned.

See also isNull() and Pixmap Transformations.

int QPixmap.serialNumber (self)

Returns a number that identifies the contents of this QPixmap object. Distinct QPixmap objects can only have the same serial number if they refer to the same contents (but they don't have to).

Warning: The serial number doesn't necessarily change when the pixmap is altered. This means that it may be dangerous to use it as a cache key. For caching pixmaps, we recommend using the QPixmapCache class whenever possible.

QPixmap.setAlphaChannel (self, QPixmap)

Sets the alpha channel of this pixmap to the given alphaChannel by converting the alphaChannel into 32 bit and using the intensity of the RGB pixel values.

The effect of this function is undefined when the pixmap is being painted on.

See also alphaChannel() and Pixmap Transformations.

QPixmap.setMask (self, QBitmap)

Sets a mask bitmap.

The newmask bitmap defines the clip mask for this pixmap. Every pixel in newmask corresponds to a pixel in this pixmap. Pixel value 1 means opaque and pixel value 0 means transparent. The mask must have the same size as this pixmap.

Warning: Setting the mask on a pixmap will cause any alpha channel data to be cleared. For example:

         QPixmap alpha("image-with-alpha.png");
         QPixmap alphacopy = alpha;
         alphacopy.setMask(alphacopy.mask());

Now, alpha and alphacopy are visually different.

Setting a null mask resets the mask.

The effect of this function is undefined when the pixmap is being painted on.

See also mask(), Pixmap Transformations, and QBitmap.

QSize QPixmap.size (self)

Returns the size of the pixmap.

See also width(), height(), and Pixmap Information.

QImage QPixmap.toImage (self)

Converts the pixmap to a QImage. Returns a null image if the conversion fails.

If the pixmap has 1-bit depth, the returned image will also be 1 bit deep. If the pixmap has 2- to 8-bit depth, the returned image has 8-bit depth. If the pixmap has greater than 8-bit depth, the returned image has 32-bit depth.

Note that for the moment, alpha masks on monochrome images are ignored.

See also fromImage() and Image Formats.

QPixmap QPixmap.transformed (self, QMatrix, Qt.TransformationMode mode = Qt.FastTransformation)

Returns a copy of the pixmap that is transformed using the given transformation matrix and transformation mode. The original pixmap is not changed.

The transformation matrix is internally adjusted to compensate for unwanted translation; i.e. the pixmap produced is the smallest pixmap that contains all the transformed points of the original pixmap. Use the trueMatrix() function to retrieve the actual matrix used for transforming the pixmap.

This function is slow because it involves transformation to a QImage, non-trivial computations and a transformation back to a QPixmap.

See also trueMatrix() and Pixmap Transformations.

QMatrix QPixmap.trueMatrix (QMatrix m, int w, int h)

Returns the actual matrix used for transforming a pixmap with the given width, height and matrix.

When transforming a pixmap using the transformed() function, the transformation matrix is internally adjusted to compensate for unwanted translation, i.e. transformed() returns the smallest pixmap containing all transformed points of the original pixmap. This function returns the modified matrix, which maps points correctly from the original pixmap into the new pixmap.

See also transformed() and Pixmap Transformations.

int QPixmap.width (self)

Returns the width of the pixmap.

See also size() and Pixmap Information.

QX11Info QPixmap.x11Info (self)

Returns information about the configuration of the X display used to display the widget.

Warning: This function is only available on X11.

See also Pixmap Information.

unsigned long QPixmap.x11PictureHandle (self)

Returns the X11 Picture handle of the pixmap for XRender support.

This function will return 0 if XRender support is not compiled into Qt, if the XRender extension is not supported on the X11 display, or if the handle could not be created. Use of this function is not portable.

Warning: This function is only available on X11.

See also Pixmap Information.


PyQt 4.1.1 for X11Copyright © Riverbank Computing Ltd and Trolltech AS 2006Qt 4.2.2