Qt logo

QPixmap Class Reference


The QPixmap class is an off-screen pixel-based paint device. More...

#include <qpixmap.h>

Inherits QPaintDevice and Qt.

Inherited by QBitmap.

List of all member functions.

Public Members

Static Public Members

Protected Members

Related Functions

(Note that these are not member functions.)

Detailed Description

The QPixmap class is an off-screen pixel-based paint device.

It is one of the two classes Qt provides for dealing with images, the other being QImage. QPixmap is designed and optimized for drawing; QImage is designed and optimized for I/O and for direct pixel access/manipulation. There are (slow) functions to convert between QImage and QPixmap; convertToImage() and convertFromImage().

One common use of the QPixmap class is to enable smooth updating of widgets. Whenever something complex needs to be drawn, you can use a pixmap to obtain flicker-free drawing, like this:

  1. Create a pixmap with the same size as the widget.
  2. Fill the pixmap with the widget background color.
  3. Paint the pixmap.
  4. bitBlt() the pixmap contents onto the widget.

Pixel data in a pixmap is internal and managed by the underlying window system. Pixels can only be accessed through QPainter functions, through bitBlt(), and by converting the QPixmap to a QImage.

You can display a QPixmap on the screen easily using e.g. QLabel::setPixmap(), and all the button classes support pixmap use.

There are also convenience functions to get and set single pixels and to load and save the entire pixmap; these work by converting the pixmap to a QImage internally.

The QPixmap class is optimized by the use of implicit sharing, so it is very efficient to pass QPixmap objects as arguments.

Note about Windows 95 and 98: Because of internal limitations in the operating system, Windows 9x easily crashes if you create around 1000 pixmaps or more. Qt will work around this problem if you set the pixmap optimization to QPixmap::MemoryOptim. Read more about this in the setOptimization() documentation.

See also: QBitmap, QImage, QImageIO and Shared Classes

Examples: qtimage/qtimage.cpp grapher/grapher.cpp xform/xform.cpp menu/menu.cpp qmag/qmag.cpp desktop/desktop.cpp scrollview/scrollview.cpp movies/main.cpp picture/picture.cpp


Member Function Documentation

QPixmap::QPixmap()

Constructs a null pixmap.

See also: isNull().

QPixmap::QPixmap(constQString&fileName, constchar*format, intconversion_flags)

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

The parameters are passed on to load().

See also: isNull(), load(), loadFromData(), save() and imageFormat().

QPixmap::QPixmap(constQString&fileName, constchar*format=0, ColorModemode=Auto)

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

The parameters are passed on to load().

See also: isNull(), load(), loadFromData(), save() and imageFormat().

QPixmap::QPixmap(constQByteArray&img_data)

Constructs a pixmaps by loading from img_data. The data can be in any image format supported by Qt.

See also: loadFromData().

QPixmap::QPixmap(constQPixmap&pixmap)

Constructs a pixmap which is a copy of pixmap.

QPixmap::QPixmap(constchar*xpm[])

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

QPixmap::QPixmap(intw, inth, constuchar*bits, boolisXbitmap) [protected]

Constructs a monochrome pixmap which is initialized with the data in bits. This constructor is protected and used by the QBitmap class.

QPixmap::QPixmap(intw, inth, intdepth=-1, Optimizationoptimization=DefaultOptim)

Constructs a pixmap with w width, h height and of depth bits per pixels.

The contents of the pixmap is uninitialized.

The depth can be either 1 (monochrome) or the depth of the current video mode. If depth is negative, then the hardware depth of the current video mode will be used.

If either width or height is zero, a null pixmap is constructed.

See also: isNull().

QPixmap::QPixmap(constQSize&size, intdepth=-1, Optimizationoptimization=DefaultOptim)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

QPixmap::~QPixmap()

Destroys the pixmap.

boolQPixmap::convertFromImage(constQImage&img, intconversion_flags)

Converts an image and sets this pixmap. Returns TRUE if successful.

The conversion_flags argument is a bitwise-OR from the following choices. The options marked (default) are the choice if no other choice from the list is included (they are zero):

Color/Mono preference (ignored for QBitmap)
Dithering mode preference, for RGB channels
Dithering mode preference, for alpha channel
Color matching versus dithering preference

Passing 0 for conversion_flags gives all the default options.

Note that even though a QPixmap with depth 1 behaves much like a QBitmap, isQBitmap() returns FALSE.

If a pixmap with depth 1 is painted with color0 and color1 and converted to an image, the pixels painted with color0 will produce pixel index 0 in the image and those painted with color1 will produce pixel index 1.

See also: convertToImage(), isQBitmap(), QImage::convertDepth(), defaultDepth() and hasAlphaBuffer().

Bugs and limitations:

Examples: qtimage/qtimage.cpp

boolQPixmap::convertFromImage(constQImage&image, ColorModemode=Auto)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

QImageQPixmap::convertToImage()const

Converts the pixmap to an image. Returns a null image if the operation failed.

If the pixmap has 1 bit depth, the returned image will also be 1 bits deep. If the pixmap has 2-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.

See also: convertFromImage().

Bugs and limitations:

Examples: qmag/qmag.cpp

QBitmapQPixmap::createHeuristicMask(boolclipTight=TRUE)const

Creates and returns a heuristic mask for this pixmap. It works by selecting a color from one of the corners, then chipping away pixels of that color, starting at all the edges.

The mask may not be perfect but should be reasonable, so you can do things like:

    pm->setMask( pm->createHeuristicMask() );

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

See also: QImage::createHeuristicMask().

intQPixmap::defaultDepth() [static]

Returns the default pixmap depth, i.e. the depth a pixmap gets if -1 is specified.

See also: depth().

intQPixmap::depth()const

Returns the depth of the image.

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(), isNull() and QImage::convertDepth().

voidQPixmap::detach() [virtual]

Special-purpose function that detaches the pixmap from shared pixmap data.

A pixmap is automatically detached by Qt whenever its contents is about to change. This is done in all QPixmap member functions that modify the pixmap (fill(), resize(), convertFromImage(), load() etc.), in bitBlt() for the destination pixmap and in QPainter::begin() on a pixmap.

It is possible to modify a pixmap without letting Qt know. You can first obtain the system-dependent handle and then call system-specific functions (for instance BitBlt under Windows) that modifies the pixmap contents. In this case, you can call detach() to cut the pixmap loose from other pixmaps that share data with this one.

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

voidQPixmap::fill(constQColor&fillColor=Qt::white)

Fills the pixmap with the color fillColor.

voidQPixmap::fill(constQWidget*widget, constQPoint&ofs)

Fills the pixmap with the widget's background color or pixmap. If the background is empty, nothing is done.

The ofs point is an offset in the widget.

The point ofs is a point in the widget's coordinate system. The pixmap's top left pixel will be mapped to the point ofs in the widget. This is significant if the widget has a background pixmap, otherwise the pixmap will simply be filled with the background color of the widget.

Example:

  void CuteWidget::paintEvent( QPaintEvent *e )
  {
    QRect ur = e->rect();               // rectangle to update

    QPixmap  pix( ur.size() );          // Pixmap for double-buffering

    pix.fill( this, ur.topLeft() );     // fill with widget background

    QPainter p( &pix );
    p.translate( -ur.x(), -ur.y() );    // use widget coordinate system
                                        // when drawing on pixmap
    //    ... draw on pixmap ...

    p.end();

    bitBlt( this, ur.topLeft(), &pix );
  }

Examples: grapher/grapher.cpp xform/xform.cpp desktop/desktop.cpp

voidQPixmap::fill(constQWidget*widget, intxofs, intyofs)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

QPixmapQPixmap::grabWindow(WIdwindow, intx=0, inty=0, intw=-1, inth=-1) [static]

Grabs the contents of a window and makes a pixmap out of it. Returns the pixmap.

The arguments (x,y) specify the offset in the window, while (w,h) specify the width and height of the area to be copied.

If w is negative, the function copies everything to the right border of the window. If h is negative, the function copies everything to the bottom of the window.

Note that grabWindows() grabs pixels from the screen, not from the window. This means that If there is another window partially or entirely over the one you grab, you get pixels from the overlying window too.

The reason we use a window identifier and not a QWidget is to enable grabbing of windows that are not part of the application.

Warning: Grabbing an area outside the window, or screen, is not safe in general. This depends on the underlying window system.

intQPixmap::height()const

Returns the height of the pixmap.

See also: width(), size() and rect().

Examples: qtimage/qtimage.cpp xform/xform.cpp desktop/desktop.cpp scrollview/scrollview.cpp movies/main.cpp

constchar*QPixmap::imageFormat(constQString&fileName) [static]

Returns a string that specifies the image format of the file fileName, or null if the file cannot be read or if the format cannot be recognized.

The QImageIO documentation lists the supported image formats.

See also: load() and save().

boolQPixmap::isNull()const

Returns TRUE if it is a null pixmap.

A null pixmap has zero width, zero height and no contents. You cannot draw in a null pixmap or bitBlt() anything to it.

Resizing an existing pixmap to (0,0) makes a pixmap into a null pixmap.

See also: resize().

Examples: qmag/qmag.cpp scrollview/scrollview.cpp

boolQPixmap::isQBitmap()const

Returns TRUE if this is a QBitmap, otherwise FALSE.

boolQPixmap::load(constQString&fileName, constchar*format, intconversion_flags)

Loads a pixmap from the file fileName. Returns TRUE if successful, or FALSE if the pixmap could not be loaded.

If format is specified, the loader attempts to read the pixmap using the specified format. If format is not specified (default), the loader reads a few bytes from the header to guess the file format.

See the convertFromImage() documentation for a description of the conversion_flags argument.

The QImageIO documentation lists the supported image formats and explains how to add extra formats.

See also: loadFromData(), save(), imageFormat(), QImage::load() and QImageIO.

Examples: xform/xform.cpp scrollview/scrollview.cpp picture/picture.cpp

boolQPixmap::load(constQString&fileName, constchar*format=0, ColorModemode=Auto)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

boolQPixmap::loadFromData(constuchar*buf, uintlen, constchar*format, intconversion_flags)

Loads a pixmap from the binary data in buf (len bytes). Returns TRUE if successful, or FALSE if the pixmap could not be loaded.

If format is specified, the loader attempts to read the pixmap using the specified format. If format is not specified (default), the loader reads a few bytes from the header to guess the file format.

See the convertFromImage() documentation for a description of the conversion_flags argument.

The QImageIO documentation lists the supported image formats and explains how to add extra formats.

See also: load(), save(), imageFormat(), QImage::loadFromData() and QImageIO.

boolQPixmap::loadFromData(constQByteArray&buf, constchar*format=0, intconversion_flags=0)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

boolQPixmap::loadFromData(constuchar*buf, uintlen, constchar*format=0, ColorModemode=Auto)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

constQBitmap*QPixmap::mask()const

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

See also: setMask() and QBitmap.

intQPixmap::metric(intm)const [virtualprotected]

Internal implementation of the virtual QPaintDevice::metric() function.

Use the QPaintDeviceMetrics class instead.

Reimplemented from QPaintDevice.

QPixmap&QPixmap::operator=(constQImage&image)

Converts the image image to a pixmap that is assigned to this pixmap. Returns a reference to the pixmap.

See also: convertFromImage().

QPixmap&QPixmap::operator=(constQPixmap&pixmap)

Assigns the pixmap pixmap to this pixmap and returns a reference to this pixmap.

QRectQPixmap::rect()const

Returns the enclosing rectangle (0,0,width(),height()) of the pixmap.

See also: width(), height() and size().

Examples: xform/xform.cpp

voidQPixmap::resize(intw, inth)

Resizes the pixmap to w width and h height. If either w or h is less than 1, the pixmap becomes a null pixmap.

If both w and h are greater than 0, a valid pixmap is created. New pixels will be uninitialized (random) if the pixmap is expanded.

Examples: grapher/grapher.cpp desktop/desktop.cpp

voidQPixmap::resize(constQSize&size)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

boolQPixmap::save(constQString&fileName, constchar*format)const

Saves the pixmap to the file fileName, using the image file format format. Returns TRUE if successful, or FALSE if the pixmap could not be saved.

See also: load(), loadFromData(), imageFormat(), QImage::save() and QImageIO.

Examples: qmag/qmag.cpp

boolQPixmap::selfMask()const

Returns TRUE if the pixmap's mask is identical to the pixmap itself.

See also: mask().

intQPixmap::serialNumber()const

Returns a number that uniquely identifies this QPixmap object. The serial number is very useful for caching.

See also: QPixmapCache.

voidQPixmap::setDefaultOptimization(Optimizationoptimization) [static]

Sets the default pixmap optimization.

All new pixmaps that are created will use this default optimization. You may also set optimization for individual pixmaps using the setOptimization() function.

The initial default optimization setting is QPixmap::Normal.

See also: defaultOptimization(), setOptimization() and optimization().

voidQPixmap::setMask(constQBitmap&newmask)

Sets a mask bitmap.

The mask bitmap defines the clip mask for this pixmap. Every pixel in mask 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.

Setting a null mask resets the mask,

See also: mask(), createHeuristicMask() and QBitmap.

voidQPixmap::setOptimization(Optimizationoptimization)

Sets pixmap drawing optimization for this pixmap.

The optimization setting affects pixmap operations, in particular drawing of transparent pixmaps (bitBlt() a pixmap with a mask set) and pixmap transformations (the xForm() function).

Pixmap optimization involves keeping intermediate results in a cache buffer and use the data in the cache to speed up bitBlt() and xForm(). The cost is more memory consumption, up to twice as much as an unoptimized pixmap.

The optimization parameter can be:

Use the setDefaultOptimization() to change the default optimization for all new pixmaps.

Note about Windows 95 and 98: On Windows 9x, the system crashes if you create around 1000 pixmaps or more, independent of the size of the pixmaps or installed RAM. The reason is that Windows 9x has a serious resource limitation that comes from the old, 64k segmented memory model. Windows NT does not have this limitation.

Qt tries to work around the resource limitation. If you set the pixmap optimization to QPixmap::MemoryOptim and the width of your pixmap is less than or equal to 128 pixels, Qt will create a logical pixmap which refers an internal pixmap. This internal pixmap is shared by hundreds of other pixmaps which have the optimization set to QPixmap::MemoryOptim. The result is that your application may use thousands of pixmaps on Windows 9x and spend only a few percent of the system resources.

When should you set the memory optimization? If your application uses hundreds of pixmaps, e.g. on tool bar buttons, in popup menus, and you plan to run it on Windows 95 or Windows 98.

Here is an example:

    QPixmap::setDefaultOptimization( QPixmap::MemoryOptim );
    while ( ... ) {
      // load tool bar pixmaps etc.
      QPixmap *pixmap = new QPixmap(fileName);
    }
    QPixmap::setDefaultOptimization( QPixmap::NormalOptim );

See also: optimization(), setDefaultOptimization() and defaultOptimization().

Examples: desktop/desktop.cpp

QSizeQPixmap::size()const

Returns the size of the pixmap.

See also: width(), height() and rect().

Examples: qtimage/qtimage.cpp movies/main.cpp

QWMatrixQPixmap::trueMatrix(constQWMatrix&matrix, intw, inth) [static]

Returns the actual matrix used for transforming a pixmap with w width and h height.

When transforming a pixmap with xForm(), the transformation matrix is internally adjusted to compensate for unwanted translation, i.e. xForm() 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: xForm() and QWMatrix.

intQPixmap::width()const

Returns the width of the pixmap.

See also: height(), size() and rect().

Examples: qtimage/qtimage.cpp xform/xform.cpp desktop/desktop.cpp scrollview/scrollview.cpp movies/main.cpp

QPixmapQPixmap::xForm(constQWMatrix&matrix)const

Returns a copy of the pixmap that is transformed using matrix.

Qt uses this function to implement rotated text on window systems that do not support such complex features.

Example of how to manually draw a rotated text at (100,200) in a widget:

    char    *str = "Trolls R Qt";       // text to be drawn
    QFont    f( "Charter", 24 );        // use Charter 24pt font
    QPixmap  pm( 8, 8 );
    QPainter p;
    QRect    r;                         // text bounding rectangle
    QPoint   bl;                        // text baseline position

    p.begin( &pm );                     // first get the bounding
    p.setFont( f );                     //   text rectangle
    r = p.fontMetrics().boundingRect(str);
    bl = -r.topLeft();                  // get baseline position
    p.end();

    pm.resize( r.size() );              // resize to fit the text
    pm.fill( white );                   // fills pm with white
    p.begin( &pm );                     // begin painting pm
    p.setFont( f );                     // set the font
    p.setPen( blue );                   // set blue text color
    p.drawText( bl, str );              // draw the text
    p.end();                            // painting done

    QWMatrix m;                         // transformation matrix
    m.rotate( -33.4 );                  // rotate coordinate system
    QPixmap rp = pm.xForm( m );         // rp is rotated pixmap

    QWMatrix t = QPixmap::trueMatrix( m, pm.width(), pm.height() );
    int x, y;
    t.map( bl.x(),bl.y(), &x,&y );      // get pm's baseline pos in rp

    bitBlt( myWidget, 100-x, 200-y,     // blt rp into a widget
            &rp, 0, 0, -1, -1 );

This example outlines how Qt implements rotated text under X11. The font calculation is the most tedious part. The rotation itself is only 3 lines of code.

If you want to draw rotated text, you do not have to implement all the code above. The code below does exactly the same thing as the example above, except that it uses a QPainter.

    char    *str = "Trolls R Qt";       // text to be drawn
    QFont    f( "Charter", 24 );        // use Charter 24pt font
    QPainter p;

    p.begin( myWidget );
    p.translate( 100, 200 );            // translates coord system
    p.rotate( -33.4 );                  // rotates it counterclockwise
    p.setFont( f );
    p.drawText( 0, 0, str );
    p.end();

See also: trueMatrix(), QWMatrix and QPainter::setWorldMatrix().

Bugs and limitations:

Examples: qtimage/qtimage.cpp xform/xform.cpp qmag/qmag.cpp desktop/desktop.cpp movies/main.cpp


Related Functions

QDataStream & operator>> (QDataStream & s, QPixmap & pixmap)

Reads a pixmap from the stream.

See also: QPixmap::load().

QDataStream & operator<< (QDataStream & s, const QPixmap & pixmap)

Writes a pixmap to the stream as a PNG image.

See also: QPixmap::save().


Search the documentation, FAQ, qt-interest archive and more (uses www.troll.no):


This file is part of the Qt toolkit, copyright © 1995-99 Troll Tech, all rights reserved.


Copyright 1999 Troll TechTrademarks
Qt version 2.0.2