1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtGui module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
40 ****************************************************************************/
45 #include "qpixmapdata_p.h"
46 #include "qimagepixmapcleanuphooks_p.h"
49 #include "qcolormap.h"
53 #include "qdatastream.h"
55 #include "qapplication.h"
56 #include <private/qapplication_p.h>
57 #include <private/qgraphicssystem_p.h>
58 #include <private/qwidget_p.h>
61 #include "qfileinfo.h"
62 #include "qpixmapcache.h"
63 #include "qdatetime.h"
64 #include "qimagereader.h"
65 #include "qimagewriter.h"
66 #include "qpaintengine.h"
70 # include "private/qt_mac_p.h"
71 # include "private/qpixmap_mac_p.h"
75 # include "qplatformintegration_qpa.h"
79 # include "qx11info_x11.h"
80 # include <private/qt_x11_p.h>
81 # include <private/qpixmap_x11_p.h>
84 #if defined(Q_OS_SYMBIAN)
85 # include <private/qt_s60_p.h>
88 #include "qpixmap_raster_p.h"
89 #include "private/qhexstring_p.h"
94 Q_GUI_EXPORT qint64 qt_pixmap_id(const QPixmap &pixmap)
96 return pixmap.cacheKey();
99 static bool qt_pixmap_thread_test()
102 qFatal("QPixmap: Must construct a QApplication before a QPaintDevice");
106 if (qApp->thread() != QThread::currentThread()) {
108 #if defined (Q_WS_X11)
109 if (!QApplication::testAttribute(Qt::AA_X11InitThreads))
111 #elif defined (Q_WS_QPA)
112 if (!QApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedPixmaps)) {
113 printf("Lighthouse plugin does not support threaded pixmaps!\n");
117 if (QApplicationPrivate::graphics_system_name != QLatin1String("raster"))
121 qWarning("QPixmap: It is not safe to use pixmaps outside the GUI thread");
128 void QPixmap::init(int w, int h, Type type)
130 init(w, h, int(type));
133 extern QApplication::Type qt_appType;
135 void QPixmap::init(int w, int h, int type)
137 if (qt_appType == QApplication::Tty) {
138 qWarning("QPixmap: Cannot create a QPixmap when no GUI is being used");
143 if ((w > 0 && h > 0) || type == QPixmapData::BitmapType)
144 data = QPixmapData::create(w, h, (QPixmapData::PixelType) type);
150 \enum QPixmap::ColorMode
154 This enum type defines the color modes that exist for converting
155 QImage objects to QPixmap. It is provided here for compatibility
156 with earlier versions of Qt.
158 Use Qt::ImageConversionFlags instead.
160 \value Auto Select \c Color or \c Mono on a case-by-case basis.
161 \value Color Always create colored pixmaps.
162 \value Mono Always create bitmaps.
166 Constructs a null pixmap.
174 (void) qt_pixmap_thread_test();
175 init(0, 0, QPixmapData::PixmapType);
179 \fn QPixmap::QPixmap(int width, int height)
181 Constructs a pixmap with the given \a width and \a height. If
182 either \a width or \a height is zero, a null pixmap is
185 \warning This will create a QPixmap with uninitialized data. Call
186 fill() to fill the pixmap with an appropriate color before drawing
187 onto it with QPainter.
192 QPixmap::QPixmap(int w, int h)
195 if (!qt_pixmap_thread_test())
196 init(0, 0, QPixmapData::PixmapType);
198 init(w, h, QPixmapData::PixmapType);
204 Constructs a pixmap of the given \a size.
206 \warning This will create a QPixmap with uninitialized data. Call
207 fill() to fill the pixmap with an appropriate color before drawing
208 onto it with QPainter.
211 QPixmap::QPixmap(const QSize &size)
214 if (!qt_pixmap_thread_test())
215 init(0, 0, QPixmapData::PixmapType);
217 init(size.width(), size.height(), QPixmapData::PixmapType);
223 QPixmap::QPixmap(const QSize &s, Type type)
225 if (!qt_pixmap_thread_test())
228 init(s.width(), s.height(), type);
234 QPixmap::QPixmap(const QSize &s, int type)
236 if (!qt_pixmap_thread_test())
237 init(0, 0, static_cast<QPixmapData::PixelType>(type));
239 init(s.width(), s.height(), static_cast<QPixmapData::PixelType>(type));
245 QPixmap::QPixmap(QPixmapData *d)
246 : QPaintDevice(), data(d)
251 Constructs a pixmap from the file with the given \a fileName. If the
252 file does not exist or is of an unknown format, the pixmap becomes a
255 The loader attempts to read the pixmap using the specified \a
256 format. If the \a format is not specified (which is the default),
257 the loader probes the file for a header to guess the file format.
259 The file name can either refer to an actual file on disk or to
260 one of the application's embedded resources. See the
261 \l{resources.html}{Resource System} overview for details on how
262 to embed images and other resource files in the application's
265 If the image needs to be modified to fit in a lower-resolution
266 result (e.g. converting from 32-bit to 8-bit), use the \a
267 flags to control the conversion.
269 The \a fileName, \a format and \a flags parameters are
270 passed on to load(). This means that the data in \a fileName is
271 not compiled into the binary. If \a fileName contains a relative
272 path (e.g. the filename only) the relevant file must be found
273 relative to the runtime working directory.
275 \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
279 QPixmap::QPixmap(const QString& fileName, const char *format, Qt::ImageConversionFlags flags)
282 init(0, 0, QPixmapData::PixmapType);
283 if (!qt_pixmap_thread_test())
286 load(fileName, format, flags);
290 Constructs a pixmap that is a copy of the given \a pixmap.
295 QPixmap::QPixmap(const QPixmap &pixmap)
298 if (!qt_pixmap_thread_test()) {
299 init(0, 0, QPixmapData::PixmapType);
302 if (pixmap.paintingActive()) { // make a deep copy
303 operator=(pixmap.copy());
310 Constructs a pixmap from the given \a xpm data, which must be a
313 Errors are silently ignored.
315 Note that it's possible to squeeze the XPM variable a little bit
316 by using an unusual declaration:
318 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 0
320 The extra \c const makes the entire definition read-only, which is
321 slightly more efficient (for example, when the code is in a shared
322 library) and ROMable when the application is to be stored in ROM.
324 #ifndef QT_NO_IMAGEFORMAT_XPM
325 QPixmap::QPixmap(const char * const xpm[])
328 init(0, 0, QPixmapData::PixmapType);
333 if (!image.isNull()) {
334 if (data && data->pixelType() == QPixmapData::BitmapType)
335 *this = QBitmap::fromImage(image);
337 *this = fromImage(image);
349 Q_ASSERT(!data || data->ref >= 1); // Catch if ref-counting changes again
355 int QPixmap::devType() const
357 return QInternal::Pixmap;
361 \fn QPixmap QPixmap::copy(int x, int y, int width, int height) const
364 Returns a deep copy of the subset of the pixmap that is specified
365 by the rectangle QRect( \a x, \a y, \a width, \a height).
369 \fn QPixmap QPixmap::copy(const QRect &rectangle) const
371 Returns a deep copy of the subset of the pixmap that is specified
372 by the given \a rectangle. For more information on deep copies,
373 see the \l {Implicit Data Sharing} documentation.
375 If the given \a rectangle is empty, the whole image is copied.
377 \sa operator=(), QPixmap(), {QPixmap#Pixmap
378 Transformations}{Pixmap Transformations}
380 QPixmap QPixmap::copy(const QRect &rect) const
385 QRect r(0, 0, width(), height());
387 r = r.intersected(rect);
389 QPixmapData *d = data->createCompatiblePixmapData();
390 d->copy(data.data(), r);
395 \fn QPixmap::scroll(int dx, int dy, int x, int y, int width, int height, QRegion *exposed)
398 This convenience function is equivalent to calling QPixmap::scroll(\a dx,
399 \a dy, QRect(\a x, \a y, \a width, \a height), \a exposed).
401 \sa QWidget::scroll(), QGraphicsItem::scroll()
407 Scrolls the area \a rect of this pixmap by (\a dx, \a dy). The exposed
408 region is left unchanged. You can optionally pass a pointer to an empty
409 QRegion to get the region that is \a exposed by the scroll operation.
411 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 2
413 You cannot scroll while there is an active painter on the pixmap.
415 \sa QWidget::scroll(), QGraphicsItem::scroll()
417 void QPixmap::scroll(int dx, int dy, const QRect &rect, QRegion *exposed)
419 if (isNull() || (dx == 0 && dy == 0))
421 QRect dest = rect & this->rect();
422 QRect src = dest.translated(-dx, -dy) & dest;
431 if (!data->scroll(dx, dy, src)) {
434 QPainter painter(&pix);
435 painter.setCompositionMode(QPainter::CompositionMode_Source);
436 painter.drawPixmap(src.translated(dx, dy), *this, src);
443 *exposed -= src.translated(dx, dy);
448 Assigns the given \a pixmap to this pixmap and returns a reference
451 \sa copy(), QPixmap()
454 QPixmap &QPixmap::operator=(const QPixmap &pixmap)
456 if (paintingActive()) {
457 qWarning("QPixmap::operator=: Cannot assign to pixmap during painting");
460 if (pixmap.paintingActive()) { // make a deep copy
461 *this = pixmap.copy();
469 \fn void QPixmap::swap(QPixmap &other)
472 Swaps pixmap \a other with this pixmap. This operation is very
473 fast and never fails.
477 Returns the pixmap as a QVariant.
479 QPixmap::operator QVariant() const
481 return QVariant(QVariant::Pixmap, this);
485 \fn bool QPixmap::operator!() const
487 Returns true if this is a null pixmap; otherwise returns false.
493 \fn QPixmap::operator QImage() const
495 Returns the pixmap as a QImage.
497 Use the toImage() function instead.
501 Converts the pixmap to a QImage. Returns a null image if the
504 If the pixmap has 1-bit depth, the returned image will also be 1
505 bit deep. Images with more bits will be returned in a format
506 closely represents the underlying system. Usually this will be
507 QImage::Format_ARGB32_Premultiplied for pixmaps with an alpha and
508 QImage::Format_RGB32 or QImage::Format_RGB16 for pixmaps without
511 Note that for the moment, alpha masks on monochrome images are
514 \sa fromImage(), {QImage#Image Formats}{Image Formats}
516 QImage QPixmap::toImage() const
521 return data->toImage();
525 \fn QMatrix QPixmap::trueMatrix(const QTransform &matrix, int width, int height)
527 Returns the actual matrix used for transforming a pixmap with the
528 given \a width, \a height and \a matrix.
530 When transforming a pixmap using the transformed() function, the
531 transformation matrix is internally adjusted to compensate for
532 unwanted translation, i.e. transformed() returns the smallest
533 pixmap containing all transformed points of the original
534 pixmap. This function returns the modified matrix, which maps
535 points correctly from the original pixmap into the new pixmap.
537 \sa transformed(), {QPixmap#Pixmap Transformations}{Pixmap
540 QTransform QPixmap::trueMatrix(const QTransform &m, int w, int h)
542 return QImage::trueMatrix(m, w, h);
548 This convenience function loads the matrix \a m into a
549 QTransform and calls the overloaded function with the
550 QTransform and the width \a w and the height \a h.
552 QMatrix QPixmap::trueMatrix(const QMatrix &m, int w, int h)
554 return trueMatrix(QTransform(m), w, h).toAffine();
559 \fn bool QPixmap::isQBitmap() const
561 Returns true if this is a QBitmap; otherwise returns false.
564 bool QPixmap::isQBitmap() const
566 return data->type == QPixmapData::BitmapType;
570 \fn bool QPixmap::isNull() const
572 Returns true if this is a null pixmap; otherwise returns false.
574 A null pixmap has zero width, zero height and no contents. You
575 cannot draw in a null pixmap.
577 bool QPixmap::isNull() const
579 return !data || data->isNull();
583 \fn int QPixmap::width() const
585 Returns the width of the pixmap.
587 \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
589 int QPixmap::width() const
591 return data ? data->width() : 0;
595 \fn int QPixmap::height() const
597 Returns the height of the pixmap.
599 \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
601 int QPixmap::height() const
603 return data ? data->height() : 0;
607 \fn QSize QPixmap::size() const
609 Returns the size of the pixmap.
611 \sa width(), height(), {QPixmap#Pixmap Information}{Pixmap
614 QSize QPixmap::size() const
616 return data ? QSize(data->width(), data->height()) : QSize(0, 0);
620 \fn QRect QPixmap::rect() const
622 Returns the pixmap's enclosing rectangle.
624 \sa {QPixmap#Pixmap Information}{Pixmap Information}
626 QRect QPixmap::rect() const
628 return data ? QRect(0, 0, data->width(), data->height()) : QRect();
632 \fn int QPixmap::depth() const
634 Returns the depth of the pixmap.
636 The pixmap depth is also called bits per pixel (bpp) or bit planes
637 of a pixmap. A null pixmap has depth 0.
639 \sa defaultDepth(), {QPixmap#Pixmap Information}{Pixmap
642 int QPixmap::depth() const
644 return data ? data->depth() : 0;
648 \fn void QPixmap::resize(const QSize &size)
652 Use QPixmap::copy() instead to get the pixmap with the new size.
657 pixmap = pixmap.copy(QRect(QPoint(0, 0), size));
661 void QPixmap::resize_helper(const QSize &s)
665 if (w < 1 || h < 1) {
673 // QPixmap.data member may be QRuntimePixmapData so use pixmapData() function to get
674 // the actual underlaying runtime pixmap data.
675 QPixmapData *pd = pixmapData();
678 QPixmap pm(QSize(w, h), pd ? pd->type : QPixmapData::PixmapType);
680 #if defined(Q_WS_X11)
681 QX11PixmapData *x11Data = pd && pd->classId() == QPixmapData::X11Class ? static_cast<QX11PixmapData*>(pd) : 0;
683 pm.x11SetScreen(x11Data->xinfo.screen());
684 uninit = x11Data->flags & QX11PixmapData::Uninitialized;
686 #elif defined(Q_WS_MAC)
687 QMacPixmapData *macData = pd && pd->classId() == QPixmapData::MacClass ? static_cast<QMacPixmapData*>(pd) : 0;
689 uninit = macData->uninit;
691 if (!uninit && !isNull()) {
693 if (hasAlphaChannel())
694 pm.fill(Qt::transparent);
696 p.drawPixmap(0, 0, *this, 0, 0, qMin(width(), w), qMin(height(), h));
699 #if defined(Q_WS_X11)
700 if (x11Data && x11Data->x11_mask) {
701 QPixmapData *newPd = pm.pixmapData();
702 QX11PixmapData *pmData = (newPd && newPd->classId() == QPixmapData::X11Class)
703 ? static_cast<QX11PixmapData*>(newPd) : 0;
705 pmData->x11_mask = (Qt::HANDLE)XCreatePixmap(X11->display,
706 RootWindow(x11Data->xinfo.display(),
707 x11Data->xinfo.screen()),
709 GC gc = XCreateGC(X11->display, pmData->x11_mask, 0, 0);
710 XCopyArea(X11->display, x11Data->x11_mask, pmData->x11_mask, gc, 0, 0,
711 qMin(width(), w), qMin(height(), h), 0, 0);
712 XFreeGC(X11->display, gc);
721 \fn void QPixmap::resize(int width, int height)
724 Use QPixmap::copy() instead to get the pixmap with the new size.
727 pixmap.resize(10, 20);
729 pixmap = pixmap.copy(0, 0, 10, 20);
734 \fn bool QPixmap::selfMask() const
737 Returns whether the pixmap is its own mask or not.
739 This function is no longer relevant since the concept of self
740 masking doesn't exists anymore.
746 This function merges the \a mask with the pixmap's alpha channel. A pixel
747 value of 1 on the mask means the pixmap's pixel is unchanged; a value of 0
748 means the pixel is transparent. The mask must have the same size as this
751 Setting a null mask resets the mask, leaving the previously transparent
752 pixels black. The effect of this function is undefined when the pixmap is
755 \warning This is potentially an expensive operation.
757 \sa mask(), {QPixmap#Pixmap Transformations}{Pixmap Transformations},
760 void QPixmap::setMask(const QBitmap &mask)
762 if (paintingActive()) {
763 qWarning("QPixmap::setMask: Cannot set mask while pixmap is being painted on");
767 if (!mask.isNull() && mask.size() != size()) {
768 qWarning("QPixmap::setMask() mask size differs from pixmap size");
775 if (static_cast<const QPixmap &>(mask).data == data) // trying to selfmask
782 #ifndef QT_NO_IMAGE_HEURISTIC_MASK
784 Creates and returns a heuristic mask for this pixmap.
786 The function works by selecting a color from one of the corners
787 and then chipping away pixels of that color, starting at all the
788 edges. If \a clipTight is true (the default) the mask is just
789 large enough to cover the pixels; otherwise, the mask is larger
790 than the data pixels.
792 The mask may not be perfect but it should be reasonable, so you
793 can do things such as the following:
795 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 1
797 This function is slow because it involves converting to/from a
798 QImage, and non-trivial computations.
800 \sa QImage::createHeuristicMask(), createMaskFromColor()
802 QBitmap QPixmap::createHeuristicMask(bool clipTight) const
804 QBitmap m = QBitmap::fromImage(toImage().createHeuristicMask(clipTight));
810 Creates and returns a mask for this pixmap based on the given \a
811 maskColor. If the \a mode is Qt::MaskInColor, all pixels matching the
812 maskColor will be transparent. If \a mode is Qt::MaskOutColor, all pixels
813 matching the maskColor will be opaque.
815 This function is slow because it involves converting to/from a
818 \sa createHeuristicMask(), QImage::createMaskFromColor()
820 QBitmap QPixmap::createMaskFromColor(const QColor &maskColor, Qt::MaskMode mode) const
822 QImage image = toImage().convertToFormat(QImage::Format_ARGB32);
823 return QBitmap::fromImage(image.createMaskFromColor(maskColor.rgba(), mode));
828 Creates and returns a mask for this pixmap based on the given \a
829 maskColor. Same as calling createMaskFromColor(maskColor,
832 \sa createHeuristicMask(), QImage::createMaskFromColor()
834 QBitmap QPixmap::createMaskFromColor(const QColor &maskColor) const
836 return createMaskFromColor(maskColor, Qt::MaskInColor);
840 Loads a pixmap from the file with the given \a fileName. Returns
841 true if the pixmap was successfully loaded; otherwise returns
844 The loader attempts to read the pixmap using the specified \a
845 format. If the \a format is not specified (which is the default),
846 the loader probes the file for a header to guess the file format.
848 The file name can either refer to an actual file on disk or to one
849 of the application's embedded resources. See the
850 \l{resources.html}{Resource System} overview for details on how to
851 embed pixmaps and other resource files in the application's
854 If the data needs to be modified to fit in a lower-resolution
855 result (e.g. converting from 32-bit to 8-bit), use the \a flags to
856 control the conversion.
858 Note that QPixmaps are automatically added to the QPixmapCache
859 when loaded from a file; the key used is internal and can not
862 \sa loadFromData(), {QPixmap#Reading and Writing Image
863 Files}{Reading and Writing Image Files}
866 bool QPixmap::load(const QString &fileName, const char *format, Qt::ImageConversionFlags flags)
868 if (fileName.isEmpty())
871 QFileInfo info(fileName);
872 QString key = QLatin1Literal("qt_pixmap")
873 % info.absoluteFilePath()
874 % HexString<uint>(info.lastModified().toTime_t())
875 % HexString<quint64>(info.size())
876 % HexString<uint>(data ? data->pixelType() : QPixmapData::PixmapType);
878 // Note: If no extension is provided, we try to match the
879 // file against known plugin extensions
880 if (!info.completeSuffix().isEmpty() && !info.exists())
883 if (QPixmapCache::find(key, *this))
886 QScopedPointer<QPixmapData> tmp(QPixmapData::create(0, 0, data ? data->type : QPixmapData::PixmapType));
887 if (tmp->fromFile(fileName, format, flags)) {
889 QPixmapCache::insert(key, *this);
897 \fn bool QPixmap::loadFromData(const uchar *data, uint len, const char *format, Qt::ImageConversionFlags flags)
899 Loads a pixmap from the \a len first bytes of the given binary \a
900 data. Returns true if the pixmap was loaded successfully;
901 otherwise returns false.
903 The loader attempts to read the pixmap using the specified \a
904 format. If the \a format is not specified (which is the default),
905 the loader probes the file for a header to guess the file format.
907 If the data needs to be modified to fit in a lower-resolution
908 result (e.g. converting from 32-bit to 8-bit), use the \a flags to
909 control the conversion.
911 \sa load(), {QPixmap#Reading and Writing Image Files}{Reading and
915 bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, Qt::ImageConversionFlags flags)
917 if (len == 0 || buf == 0)
921 data = QPixmapData::create(0, 0, QPixmapData::PixmapType);
923 return data->fromData(buf, len, format, flags);
927 \fn bool QPixmap::loadFromData(const QByteArray &data, const char *format, Qt::ImageConversionFlags flags)
931 Loads a pixmap from the binary \a data using the specified \a
932 format and conversion \a flags.
937 Saves the pixmap to the file with the given \a fileName using the
938 specified image file \a format and \a quality factor. Returns true
939 if successful; otherwise returns false.
941 The \a quality factor must be in the range [0,100] or -1. Specify
942 0 to obtain small compressed files, 100 for large uncompressed
943 files, and -1 to use the default settings.
945 If \a format is 0, an image format will be chosen from \a fileName's
948 \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
952 bool QPixmap::save(const QString &fileName, const char *format, int quality) const
955 return false; // nothing to save
956 QImageWriter writer(fileName, format);
957 return doImageIO(&writer, quality);
963 This function writes a QPixmap to the given \a device using the
964 specified image file \a format and \a quality factor. This can be
965 used, for example, to save a pixmap directly into a QByteArray:
967 \snippet doc/src/snippets/image/image.cpp 1
970 bool QPixmap::save(QIODevice* device, const char* format, int quality) const
973 return false; // nothing to save
974 QImageWriter writer(device, format);
975 return doImageIO(&writer, quality);
980 bool QPixmap::doImageIO(QImageWriter *writer, int quality) const
982 if (quality > 100 || quality < -1)
983 qWarning("QPixmap::save: quality out of range [-1,100]");
985 writer->setQuality(qMin(quality,100));
986 return writer->write(toImage());
990 // The implementation (and documentation) of
991 // QPixmap::fill(const QWidget *, const QPoint &)
995 \fn void QPixmap::fill(const QWidget *widget, int x, int y)
998 Fills the pixmap with the \a widget's background color or pixmap.
999 The given point, (\a x, \a y), defines an offset in widget
1000 coordinates to which the pixmap's top-left pixel will be mapped
1005 Fills the pixmap with the given \a color.
1007 The effect of this function is undefined when the pixmap is
1010 \sa {QPixmap#Pixmap Transformations}{Pixmap Transformations}
1013 void QPixmap::fill(const QColor &color)
1018 // Some people are probably already calling fill while a painter is active, so to not break
1019 // their programs, only print a warning and return when the fill operation could cause a crash.
1020 if (paintingActive() && (color.alpha() != 255) && !hasAlphaChannel()) {
1021 qWarning("QPixmap::fill: Cannot fill while pixmap is being painted on");
1025 if (data->ref == 1) {
1026 // detach() will also remove this pixmap from caches, so
1027 // it has to be called even when ref == 1.
1030 // Don't bother to make a copy of the data object, since
1031 // it will be filled with new pixel data anyway.
1032 QPixmapData *d = data->createCompatiblePixmapData();
1033 d->resize(data->width(), data->height());
1040 Returns a number that identifies the contents of this QPixmap
1041 object. Distinct QPixmap objects can only have the same serial
1042 number if they refer to the same contents (but they don't have
1045 Use cacheKey() instead.
1047 \warning The serial number doesn't necessarily change when
1048 the pixmap is altered. This means that it may be dangerous to use
1049 it as a cache key. For caching pixmaps, we recommend using the
1050 QPixmapCache class whenever possible.
1052 int QPixmap::serialNumber() const
1056 return data->serialNumber();
1060 Returns a number that identifies this QPixmap. Distinct QPixmap
1061 objects can only have the same cache key if they refer to the same
1064 The cacheKey() will change when the pixmap is altered.
1066 qint64 QPixmap::cacheKey() const
1072 return data->cacheKey();
1075 static void sendResizeEvents(QWidget *target)
1077 QResizeEvent e(target->size(), QSize());
1078 QApplication::sendEvent(target, &e);
1080 const QObjectList children = target->children();
1081 for (int i = 0; i < children.size(); ++i) {
1082 QWidget *child = static_cast<QWidget*>(children.at(i));
1083 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
1084 sendResizeEvents(child);
1089 \fn QPixmap QPixmap::grabWidget(QWidget * widget, const QRect &rectangle)
1091 Creates a pixmap and paints the given \a widget, restricted by the
1092 given \a rectangle, in it. If the \a widget has any children, then
1093 they are also painted in the appropriate positions.
1095 If no rectangle is specified (the default) the entire widget is
1098 If \a widget is 0, the specified rectangle doesn't overlap the
1099 widget's rectangle, or an error occurs, the function will return a
1100 null QPixmap. If the rectangle is a superset of the given \a
1101 widget, the areas outside the \a widget are covered with the
1102 widget's background.
1104 This function actually asks \a widget to paint itself (and its
1105 children to paint themselves) by calling paintEvent() with painter
1106 redirection turned on. But QPixmap also provides the grabWindow()
1107 function which is a bit faster by grabbing pixels directly off the
1108 screen. In addition, if there are overlaying windows,
1109 grabWindow(), unlike grabWidget(), will see them.
1111 \warning Do not grab a widget from its QWidget::paintEvent().
1112 However, it is safe to grab a widget from another widget's
1113 \l {QWidget::}{paintEvent()}.
1118 QPixmap QPixmap::grabWidget(QWidget * widget, const QRect &rect)
1123 if (widget->testAttribute(Qt::WA_PendingResizeEvent) || !widget->testAttribute(Qt::WA_WState_Created))
1124 sendResizeEvents(widget);
1126 widget->d_func()->prepareToRender(QRegion(),
1127 QWidget::DrawWindowBackground | QWidget::DrawChildren | QWidget::IgnoreMask);
1131 r.setWidth(widget->width() - rect.x());
1133 r.setHeight(widget->height() - rect.y());
1135 if (!r.intersects(widget->rect()))
1138 QPixmap res(r.size());
1139 if (!qt_widget_private(widget)->isOpaque)
1140 res.fill(Qt::transparent);
1142 widget->d_func()->render(&res, QPoint(), r, QWidget::DrawWindowBackground
1143 | QWidget::DrawChildren | QWidget::IgnoreMask, true);
1148 \fn QPixmap QPixmap::grabWidget(QWidget *widget, int x, int y, int
1153 Creates a pixmap and paints the given \a widget, restricted by
1154 QRect(\a x, \a y, \a width, \a height), in it.
1156 \warning Do not grab a widget from its QWidget::paintEvent().
1157 However, it is safe to grab a widget from another widget's
1158 \l {QWidget::}{paintEvent()}.
1165 \enum QPixmap::ShareMode
1167 This enum type defines the share modes that are available when
1168 creating a QPixmap object from a raw X11 Pixmap handle.
1170 \value ImplicitlyShared This mode will cause the QPixmap object to
1171 create a copy of the internal data before it is modified, thus
1172 keeping the original X11 pixmap intact.
1174 \value ExplicitlyShared In this mode, the pixmap data will \e not be
1175 copied before it is modified, which in effect will change the
1176 original X11 pixmap.
1178 \warning This enum is only used for X11 specific functions; using
1181 \sa QPixmap::fromX11Pixmap()
1187 \fn QPixmap QPixmap::fromX11Pixmap(Qt::HANDLE pixmap, QPixmap::ShareMode mode)
1189 Creates a QPixmap from the native X11 Pixmap handle \a pixmap,
1190 using \a mode as the share mode. The default share mode is
1191 QPixmap::ImplicitlyShared, which means that a copy of the pixmap is
1192 made if someone tries to modify it by e.g. drawing onto it.
1194 QPixmap does \e not take ownership of the \a pixmap handle, and
1195 have to be deleted by the user.
1197 \warning This function is X11 specific; using it is non-portable.
1199 \sa QPixmap::ShareMode
1203 #if defined(Q_WS_X11) || defined(Q_WS_QWS)
1206 Returns the pixmap's handle to the device context.
1208 Note that, since QPixmap make use of \l {Implicit Data
1209 Sharing}{implicit data sharing}, the detach() function must be
1210 called explicitly to ensure that only \e this pixmap's data is
1211 modified if the pixmap data is shared.
1213 \warning This function is X11 specific; using it is non-portable.
1215 \warning Since 4.8, pixmaps do not have an X11 handle unless
1216 created with \l {QPixmap::}{fromX11Pixmap()}, or if the native
1217 graphics system is explicitly enabled.
1220 \sa QApplication::setGraphicsSystem()
1223 Qt::HANDLE QPixmap::handle() const
1225 #if defined(Q_WS_X11)
1226 const QPixmapData *pd = pixmapData();
1228 if (pd->classId() == QPixmapData::X11Class)
1229 return static_cast<const QX11PixmapData*>(pd)->handle();
1231 qWarning("QPixmap::handle(): Pixmap is not an X11 class pixmap");
1240 static Qt::ImageConversionFlags colorModeToFlags(QPixmap::ColorMode mode)
1242 Qt::ImageConversionFlags flags = Qt::AutoColor;
1244 case QPixmap::Color:
1245 flags |= Qt::ColorOnly;
1248 flags |= Qt::MonoOnly;
1257 Use the constructor that takes a Qt::ImageConversionFlag instead.
1260 QPixmap::QPixmap(const QString& fileName, const char *format, ColorMode mode)
1263 init(0, 0, QPixmapData::PixmapType);
1264 if (!qt_pixmap_thread_test())
1267 load(fileName, format, colorModeToFlags(mode));
1271 Constructs a pixmap from the QImage \a image.
1273 Use the static fromImage() function instead.
1275 QPixmap::QPixmap(const QImage& image)
1278 init(0, 0, QPixmapData::PixmapType);
1279 if (!qt_pixmap_thread_test())
1282 if (data && data->pixelType() == QPixmapData::BitmapType)
1283 *this = QBitmap::fromImage(image);
1285 *this = fromImage(image);
1291 Converts the given \a image to a pixmap that is assigned to this
1294 Use the static fromImage() function instead.
1297 QPixmap &QPixmap::operator=(const QImage &image)
1299 if (data && data->pixelType() == QPixmapData::BitmapType)
1300 *this = QBitmap::fromImage(image);
1302 *this = fromImage(image);
1307 Use the load() function that takes a Qt::ImageConversionFlag instead.
1310 bool QPixmap::load(const QString &fileName, const char *format, ColorMode mode)
1312 return load(fileName, format, colorModeToFlags(mode));
1316 Use the loadFromData() function that takes a Qt::ImageConversionFlag instead.
1319 bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, ColorMode mode)
1321 return loadFromData(buf, len, format, colorModeToFlags(mode));
1325 Use the static fromImage() function instead.
1327 bool QPixmap::convertFromImage(const QImage &image, ColorMode mode)
1329 if (data && data->pixelType() == QPixmapData::BitmapType)
1330 *this = QBitmap::fromImage(image, colorModeToFlags(mode));
1332 *this = fromImage(image, colorModeToFlags(mode));
1338 /*****************************************************************************
1339 QPixmap stream functions
1340 *****************************************************************************/
1341 #if !defined(QT_NO_DATASTREAM)
1345 Writes the given \a pixmap to the given \a stream as a PNG
1346 image. Note that writing the stream to a file will not produce a
1349 \sa QPixmap::save(), {Serializing Qt Data Types}
1352 QDataStream &operator<<(QDataStream &stream, const QPixmap &pixmap)
1354 return stream << pixmap.toImage();
1360 Reads an image from the given \a stream into the given \a pixmap.
1362 \sa QPixmap::load(), {Serializing Qt Data Types}
1365 QDataStream &operator>>(QDataStream &stream, QPixmap &pixmap)
1370 if (image.isNull()) {
1372 } else if (image.depth() == 1) {
1373 pixmap = QBitmap::fromImage(image);
1375 pixmap = QPixmap::fromImage(image);
1380 #endif // QT_NO_DATASTREAM
1383 Q_GUI_EXPORT void copyBlt(QPixmap *dst, int dx, int dy,
1384 const QPixmap *src, int sx, int sy, int sw, int sh)
1386 Q_ASSERT_X(dst, "::copyBlt", "Destination pixmap must be non-null");
1387 Q_ASSERT_X(src, "::copyBlt", "Source pixmap must be non-null");
1389 if (src->hasAlphaChannel()) {
1390 if (dst->paintEngine()->hasFeature(QPaintEngine::PorterDuff)) {
1392 p.setCompositionMode(QPainter::CompositionMode_Source);
1393 p.drawPixmap(dx, dy, *src, sx, sy, sw, sh);
1395 QImage image = dst->toImage().convertToFormat(QImage::Format_ARGB32_Premultiplied);
1397 p.setCompositionMode(QPainter::CompositionMode_Source);
1398 p.drawPixmap(dx, dy, *src, sx, sy, sw, sh);
1400 *dst = QPixmap::fromImage(image);
1404 p.drawPixmap(dx, dy, *src, sx, sy, sw, sh);
1414 bool QPixmap::isDetached() const
1416 return data && data->ref == 1;
1420 ### Qt5 - remove me.
1422 void QPixmap::deref()
1424 Q_ASSERT_X(false, "QPixmap::deref()", "Do not call this function anymore!");
1428 \fn QImage QPixmap::convertToImage() const
1430 Use the toImage() function instead.
1434 Replaces this pixmap's data with the given \a image using the
1435 specified \a flags to control the conversion. The \a flags
1436 argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}.
1437 Passing 0 for \a flags sets all the default options. Returns true
1438 if the result is that this pixmap is not null.
1440 Note: this function was part of Qt 3 support in Qt 4.6 and earlier.
1441 It has been promoted to official API status in 4.7 to support updating
1442 the pixmap's image without creating a new QPixmap as fromImage() would.
1447 bool QPixmap::convertFromImage(const QImage &image, Qt::ImageConversionFlags flags)
1449 if (image.isNull() || !data)
1450 *this = QPixmap::fromImage(image, flags);
1452 data->fromImage(image, flags);
1457 \fn QPixmap QPixmap::xForm(const QMatrix &matrix) const
1459 Use transformed() instead.
1463 \fn QPixmap QPixmap::scaled(int width, int height,
1464 Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode
1465 transformMode) const
1469 Returns a copy of the pixmap scaled to a rectangle with the given
1470 \a width and \a height according to the given \a aspectRatioMode and
1473 If either the \a width or the \a height is zero or negative, this
1474 function returns a null pixmap.
1478 \fn QPixmap QPixmap::scaled(const QSize &size, Qt::AspectRatioMode
1479 aspectRatioMode, Qt::TransformationMode transformMode) const
1481 Scales the pixmap to the given \a size, using the aspect ratio and
1482 transformation modes specified by \a aspectRatioMode and \a
1485 \image qimage-scaling.png
1488 \i If \a aspectRatioMode is Qt::IgnoreAspectRatio, the pixmap
1489 is scaled to \a size.
1490 \i If \a aspectRatioMode is Qt::KeepAspectRatio, the pixmap is
1491 scaled to a rectangle as large as possible inside \a size, preserving the aspect ratio.
1492 \i If \a aspectRatioMode is Qt::KeepAspectRatioByExpanding,
1493 the pixmap is scaled to a rectangle as small as possible
1494 outside \a size, preserving the aspect ratio.
1497 If the given \a size is empty, this function returns a null
1501 In some cases it can be more beneficial to draw the pixmap to a
1502 painter with a scale set rather than scaling the pixmap. This is
1503 the case when the painter is for instance based on OpenGL or when
1504 the scale factor changes rapidly.
1506 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1510 QPixmap QPixmap::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::TransformationMode mode) const
1513 qWarning("QPixmap::scaled: Pixmap is a null pixmap");
1519 QSize newSize = size();
1520 newSize.scale(s, aspectMode);
1521 if (newSize == size())
1524 QTransform wm = QTransform::fromScale((qreal)newSize.width() / width(),
1525 (qreal)newSize.height() / height());
1526 QPixmap pix = transformed(wm, mode);
1531 \fn QPixmap QPixmap::scaledToWidth(int width, Qt::TransformationMode
1534 Returns a scaled copy of the image. The returned image is scaled
1535 to the given \a width using the specified transformation \a mode.
1536 The height of the pixmap is automatically calculated so that the
1537 aspect ratio of the pixmap is preserved.
1539 If \a width is 0 or negative, a null pixmap is returned.
1541 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1544 QPixmap QPixmap::scaledToWidth(int w, Qt::TransformationMode mode) const
1547 qWarning("QPixmap::scaleWidth: Pixmap is a null pixmap");
1553 qreal factor = (qreal) w / width();
1554 QTransform wm = QTransform::fromScale(factor, factor);
1555 return transformed(wm, mode);
1559 \fn QPixmap QPixmap::scaledToHeight(int height,
1560 Qt::TransformationMode mode) const
1562 Returns a scaled copy of the image. The returned image is scaled
1563 to the given \a height using the specified transformation \a mode.
1564 The width of the pixmap is automatically calculated so that the
1565 aspect ratio of the pixmap is preserved.
1567 If \a height is 0 or negative, a null pixmap is returned.
1569 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1572 QPixmap QPixmap::scaledToHeight(int h, Qt::TransformationMode mode) const
1575 qWarning("QPixmap::scaleHeight: Pixmap is a null pixmap");
1581 qreal factor = (qreal) h / height();
1582 QTransform wm = QTransform::fromScale(factor, factor);
1583 return transformed(wm, mode);
1587 Returns a copy of the pixmap that is transformed using the given
1588 transformation \a transform and transformation \a mode. The original
1589 pixmap is not changed.
1591 The transformation \a transform is internally adjusted to compensate
1592 for unwanted translation; i.e. the pixmap produced is the smallest
1593 pixmap that contains all the transformed points of the original
1594 pixmap. Use the trueMatrix() function to retrieve the actual
1595 matrix used for transforming the pixmap.
1597 This function is slow because it involves transformation to a
1598 QImage, non-trivial computations and a transformation back to a
1601 \sa trueMatrix(), {QPixmap#Pixmap Transformations}{Pixmap
1604 QPixmap QPixmap::transformed(const QTransform &transform,
1605 Qt::TransformationMode mode) const
1607 if (isNull() || transform.type() <= QTransform::TxTranslate)
1610 return data->transformed(transform, mode);
1616 This convenience function loads the \a matrix into a
1617 QTransform and calls the overloaded function.
1619 QPixmap QPixmap::transformed(const QMatrix &matrix, Qt::TransformationMode mode) const
1621 return transformed(QTransform(matrix), mode);
1634 \brief The QPixmap class is an off-screen image representation
1635 that can be used as a paint device.
1641 Qt provides four classes for handling image data: QImage, QPixmap,
1642 QBitmap and QPicture. QImage is designed and optimized for I/O,
1643 and for direct pixel access and manipulation, while QPixmap is
1644 designed and optimized for showing images on screen. QBitmap is
1645 only a convenience class that inherits QPixmap, ensuring a depth
1646 of 1. The isQBitmap() function returns true if a QPixmap object is
1647 really a bitmap, otherwise returns false. Finally, the QPicture class
1648 is a paint device that records and replays QPainter commands.
1650 A QPixmap can easily be displayed on the screen using QLabel or
1651 one of QAbstractButton's subclasses (such as QPushButton and
1652 QToolButton). QLabel has a pixmap property, whereas
1653 QAbstractButton has an icon property.
1655 In addition to the ordinary constructors, a QPixmap can be
1656 constructed using the static grabWidget() and grabWindow()
1657 functions which creates a QPixmap and paints the given widget, or
1660 QPixmap objects can be passed around by value since the QPixmap
1661 class uses implicit data sharing. For more information, see the \l
1662 {Implicit Data Sharing} documentation. QPixmap objects can also be
1665 Note that the pixel data in a pixmap is internal and is managed by
1666 the underlying window system. Because QPixmap is a QPaintDevice
1667 subclass, QPainter can be used to draw directly onto pixmaps.
1668 Pixels can only be accessed through QPainter functions or by
1669 converting the QPixmap to a QImage. However, the fill() function
1670 is available for initializing the entire pixmap with a given color.
1672 There are functions to convert between QImage and
1673 QPixmap. Typically, the QImage class is used to load an image
1674 file, optionally manipulating the image data, before the QImage
1675 object is converted into a QPixmap to be shown on
1676 screen. Alternatively, if no manipulation is desired, the image
1677 file can be loaded directly into a QPixmap. On Windows, the
1678 QPixmap class also supports conversion between \c HBITMAP and
1679 QPixmap. On Symbian, the QPixmap class also supports conversion
1680 between CFbsBitmap and QPixmap.
1682 QPixmap provides a collection of functions that can be used to
1683 obtain a variety of information about the pixmap. In addition,
1684 there are several functions that enables transformation of the
1689 \section1 Reading and Writing Image Files
1691 QPixmap provides several ways of reading an image file: The file
1692 can be loaded when constructing the QPixmap object, or by using
1693 the load() or loadFromData() functions later on. When loading an
1694 image, the file name can either refer to an actual file on disk or
1695 to one of the application's embedded resources. See \l{The Qt
1696 Resource System} overview for details on how to embed images and
1697 other resource files in the application's executable.
1699 Simply call the save() function to save a QPixmap object.
1701 The complete list of supported file formats are available through
1702 the QImageReader::supportedImageFormats() and
1703 QImageWriter::supportedImageFormats() functions. New file formats
1704 can be added as plugins. By default, Qt supports the following
1708 \header \o Format \o Description \o Qt's support
1709 \row \o BMP \o Windows Bitmap \o Read/write
1710 \row \o GIF \o Graphic Interchange Format (optional) \o Read
1711 \row \o JPG \o Joint Photographic Experts Group \o Read/write
1712 \row \o JPEG \o Joint Photographic Experts Group \o Read/write
1713 \row \o PNG \o Portable Network Graphics \o Read/write
1714 \row \o PBM \o Portable Bitmap \o Read
1715 \row \o PGM \o Portable Graymap \o Read
1716 \row \o PPM \o Portable Pixmap \o Read/write
1717 \row \o XBM \o X11 Bitmap \o Read/write
1718 \row \o XPM \o X11 Pixmap \o Read/write
1721 \section1 Pixmap Information
1723 QPixmap provides a collection of functions that can be used to
1724 obtain a variety of information about the pixmap:
1728 \o \o Available Functions
1732 The size(), width() and height() functions provide information
1733 about the pixmap's size. The rect() function returns the image's
1734 enclosing rectangle.
1740 The hasAlphaChannel() returns true if the pixmap has a format that
1741 respects the alpha channel, otherwise returns false. The hasAlpha(),
1742 setMask() and mask() functions are legacy and should not be used.
1743 They are potentially very slow.
1745 The createHeuristicMask() function creates and returns a 1-bpp
1746 heuristic mask (i.e. a QBitmap) for this pixmap. It works by
1747 selecting a color from one of the corners and then chipping away
1748 pixels of that color, starting at all the edges. The
1749 createMaskFromColor() function creates and returns a mask (i.e. a
1750 QBitmap) for the pixmap based on a given color.
1753 \o Low-level information
1756 The depth() function returns the depth of the pixmap. The
1757 defaultDepth() function returns the default depth, i.e. the depth
1758 used by the application on the given screen.
1760 The cacheKey() function returns a number that uniquely
1761 identifies the contents of the QPixmap object.
1763 The x11Info() function returns information about the configuration
1764 of the X display used by the screen to which the pixmap currently
1765 belongs. The x11PictureHandle() function returns the X11 Picture
1766 handle of the pixmap for XRender support. Note that the two latter
1767 functions are only available on x11.
1771 \section1 Pixmap Conversion
1773 A QPixmap object can be converted into a QImage using the
1774 toImage() function. Likewise, a QImage can be converted into a
1775 QPixmap using the fromImage(). If this is too expensive an
1776 operation, you can use QBitmap::fromImage() instead.
1778 In addition, on Windows, the QPixmap class supports conversion to
1779 and from HBITMAP: the toWinHBITMAP() function creates a HBITMAP
1780 equivalent to the QPixmap, based on the given HBitmapFormat, and
1781 returns the HBITMAP handle. The fromWinHBITMAP() function returns
1782 a QPixmap that is equivalent to the given bitmap which has the
1783 specified format. The QPixmap class also supports conversion to
1784 and from HICON: the toWinHICON() function creates a HICON equivalent
1785 to the QPixmap, and returns the HICON handle. The fromWinHICON()
1786 function returns a QPixmap that is equivalent to the given icon.
1788 In addition, on Symbian, the QPixmap class supports conversion to
1789 and from CFbsBitmap: the toSymbianCFbsBitmap() function creates
1790 CFbsBitmap equivalent to the QPixmap, based on given mode and returns
1791 a CFbsBitmap object. The fromSymbianCFbsBitmap() function returns a
1792 QPixmap that is equivalent to the given bitmap and given mode.
1794 \section1 Pixmap Transformations
1796 QPixmap supports a number of functions for creating a new pixmap
1797 that is a transformed version of the original:
1799 The scaled(), scaledToWidth() and scaledToHeight() functions
1800 return scaled copies of the pixmap, while the copy() function
1801 creates a QPixmap that is a plain copy of the original one.
1803 The transformed() function returns a copy of the pixmap that is
1804 transformed with the given transformation matrix and
1805 transformation mode: Internally, the transformation matrix is
1806 adjusted to compensate for unwanted translation,
1807 i.e. transformed() returns the smallest pixmap containing all
1808 transformed points of the original pixmap. The static trueMatrix()
1809 function returns the actual matrix used for transforming the
1812 \note When using the native X11 graphics system, the pixmap
1813 becomes invalid when the QApplication instance is destroyed.
1815 \sa QBitmap, QImage, QImageReader, QImageWriter
1820 \typedef QPixmap::DataPtr
1825 \fn DataPtr &QPixmap::data_ptr()
1830 Returns true if this pixmap has an alpha channel, \e or has a
1831 mask, otherwise returns false.
1833 \sa hasAlphaChannel(), mask()
1835 bool QPixmap::hasAlpha() const
1837 #if defined(Q_WS_X11)
1838 if (data && data->hasAlphaChannel())
1840 QPixmapData *pd = pixmapData();
1841 if (pd && pd->classId() == QPixmapData::X11Class) {
1842 QX11PixmapData *x11Data = static_cast<QX11PixmapData*>(pd);
1843 #ifndef QT_NO_XRENDER
1844 if (x11Data->picture && x11Data->d == 32)
1847 if (x11Data->d == 1 || x11Data->x11_mask)
1852 return data && data->hasAlphaChannel();
1857 Returns true if the pixmap has a format that respects the alpha
1858 channel, otherwise returns false.
1862 bool QPixmap::hasAlphaChannel() const
1864 return data && data->hasAlphaChannel();
1870 int QPixmap::metric(PaintDeviceMetric metric) const
1872 return data ? data->metric(metric) : 0;
1876 \fn void QPixmap::setAlphaChannel(const QPixmap &alphaChannel)
1879 Sets the alpha channel of this pixmap to the given \a alphaChannel
1880 by converting the \a alphaChannel into 32 bit and using the
1881 intensity of the RGB pixel values.
1883 The effect of this function is undefined when the pixmap is being
1886 \warning This is potentially an expensive operation. Most usecases
1887 for this function are covered by QPainter and compositionModes
1888 which will normally execute faster.
1890 \sa alphaChannel(), {QPixmap#Pixmap Transformations}{Pixmap
1893 void QPixmap::setAlphaChannel(const QPixmap &alphaChannel)
1895 if (alphaChannel.isNull())
1898 if (paintingActive()) {
1899 qWarning("QPixmap::setAlphaChannel: "
1900 "Cannot set alpha channel while pixmap is being painted on");
1904 if (width() != alphaChannel.width() && height() != alphaChannel.height()) {
1905 qWarning("QPixmap::setAlphaChannel: "
1906 "The pixmap and the alpha channel pixmap must have the same size");
1911 data->setAlphaChannel(alphaChannel);
1917 Returns the alpha channel of the pixmap as a new grayscale QPixmap in which
1918 each pixel's red, green, and blue values are given the alpha value of the
1919 original pixmap. The color depth of the returned pixmap is the system depth
1920 on X11 and 8-bit on Windows and Mac OS X.
1922 You can use this function while debugging
1923 to get a visible image of the alpha channel. If the pixmap doesn't have an
1924 alpha channel, i.e., the alpha channel's value for all pixels equals
1925 0xff), a null pixmap is returned. You can check this with the \c isNull()
1930 \snippet doc/src/snippets/alphachannel.cpp 0
1932 \image alphachannelimage.png The pixmap and channelImage QPixmaps
1934 \warning This is an expensive operation. The alpha channel of the
1935 pixmap is extracted dynamically from the pixeldata. Most usecases of this
1936 function are covered by QPainter and compositionModes which will normally
1939 \sa setAlphaChannel(), {QPixmap#Pixmap Information}{Pixmap
1942 QPixmap QPixmap::alphaChannel() const
1944 return data ? data->alphaChannel() : QPixmap();
1950 QPaintEngine *QPixmap::paintEngine() const
1952 return data ? data->paintEngine() : 0;
1956 \fn QBitmap QPixmap::mask() const
1958 Extracts a bitmap mask from the pixmap's alpha channel.
1960 \warning This is potentially an expensive operation. The mask of
1961 the pixmap is extracted dynamically from the pixeldata.
1963 \sa setMask(), {QPixmap#Pixmap Information}{Pixmap Information}
1965 QBitmap QPixmap::mask() const
1967 return data ? data->mask() : QBitmap();
1971 Returns the default pixmap depth used by the application.
1973 On Windows and Mac, the default depth is always 32. On X11 and
1974 embedded, the depth of the screen will be returned by this
1977 \sa depth(), QColormap::depth(), {QPixmap#Pixmap Information}{Pixmap Information}
1980 int QPixmap::defaultDepth()
1982 #if defined(Q_WS_QWS)
1983 return QScreen::instance()->depth();
1984 #elif defined(Q_WS_X11)
1985 return QX11Info::appDepth();
1986 #elif defined(Q_WS_WINCE)
1987 return QColormap::instance().depth();
1988 #elif defined(Q_WS_WIN)
1990 #elif defined(Q_WS_MAC)
1992 #elif defined(Q_OS_SYMBIAN)
1993 return S60->screenDepth;
1994 #elif defined(Q_WS_QPA)
1995 return 32; //LITE: use graphicssystem (we should do that in general)
2000 Detaches the pixmap from shared pixmap data.
2002 A pixmap is automatically detached by Qt whenever its contents are
2003 about to change. This is done in almost all QPixmap member
2004 functions that modify the pixmap (fill(), fromImage(),
2005 load(), etc.), and in QPainter::begin() on a pixmap.
2007 There are two exceptions in which detach() must be called
2008 explicitly, that is when calling the handle() or the
2009 x11PictureHandle() function (only available on X11). Otherwise,
2010 any modifications done using system calls, will be performed on
2013 The detach() function returns immediately if there is just a
2014 single reference or if the pixmap has not been initialized yet.
2016 void QPixmap::detach()
2021 // QPixmap.data member may be QRuntimePixmapData so use pixmapData() function to get
2022 // the actual underlaying runtime pixmap data.
2023 QPixmapData *pd = pixmapData();
2024 QPixmapData::ClassId id = pd->classId();
2025 if (id == QPixmapData::RasterClass) {
2026 QRasterPixmapData *rasterData = static_cast<QRasterPixmapData*>(pd);
2027 rasterData->image.detach();
2030 if (data->is_cached && data->ref == 1)
2031 QImagePixmapCleanupHooks::executePixmapDataModificationHooks(data.data());
2033 #if defined(Q_WS_MAC)
2034 QMacPixmapData *macData = id == QPixmapData::MacClass ? static_cast<QMacPixmapData*>(pd) : 0;
2036 if (macData->cg_mask) {
2037 CGImageRelease(macData->cg_mask);
2038 macData->cg_mask = 0;
2043 if (data->ref != 1) {
2048 #if defined(Q_WS_X11)
2049 if (pd->classId() == QPixmapData::X11Class) {
2050 QX11PixmapData *d = static_cast<QX11PixmapData*>(pd);
2051 d->flags &= ~QX11PixmapData::Uninitialized;
2053 // reset the cache data
2055 XFreePixmap(X11->display, d->hd2);
2059 #elif defined(Q_WS_MAC)
2061 macData->macReleaseCGImageRef();
2062 macData->uninit = false;
2068 \fn QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
2070 Converts the given \a image to a pixmap using the specified \a
2071 flags to control the conversion. The \a flags argument is a
2072 bitwise-OR of the \l{Qt::ImageConversionFlags}. Passing 0 for \a
2073 flags sets all the default options.
2075 In case of monochrome and 8-bit images, the image is first
2076 converted to a 32-bit pixmap and then filled with the colors in
2077 the color table. If this is too expensive an operation, you can
2078 use QBitmap::fromImage() instead.
2080 \sa fromImageReader(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2082 QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
2087 QGraphicsSystem* gs = QApplicationPrivate::graphicsSystem();
2088 QScopedPointer<QPixmapData> data(gs ? gs->createPixmapData(QPixmapData::PixmapType)
2089 : QGraphicsSystem::createDefaultPixmapData(QPixmapData::PixmapType));
2090 data->fromImage(image, flags);
2091 return QPixmap(data.take());
2095 \fn QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags)
2097 Create a QPixmap from an image read directly from an \a imageReader.
2098 The \a flags argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}.
2099 Passing 0 for \a flags sets all the default options.
2101 On some systems, reading an image directly to QPixmap can use less memory than
2102 reading a QImage to convert it to QPixmap.
2104 \sa fromImage(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2106 QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags)
2108 QGraphicsSystem *gs = QApplicationPrivate::graphicsSystem();
2109 QScopedPointer<QPixmapData> data(gs ? gs->createPixmapData(QPixmapData::PixmapType)
2110 : QGraphicsSystem::createDefaultPixmapData(QPixmapData::PixmapType));
2111 data->fromImageReader(imageReader, flags);
2112 return QPixmap(data.take());
2116 \fn QPixmap QPixmap::grabWindow(WId window, int x, int y, int
2119 Creates and returns a pixmap constructed by grabbing the contents
2120 of the given \a window restricted by QRect(\a x, \a y, \a width,
2123 The arguments (\a{x}, \a{y}) specify the offset in the window,
2124 whereas (\a{width}, \a{height}) specify the area to be copied. If
2125 \a width is negative, the function copies everything to the right
2126 border of the window. If \a height is negative, the function
2127 copies everything to the bottom of the window.
2129 The window system identifier (\c WId) can be retrieved using the
2130 QWidget::winId() function. The rationale for using a window
2131 identifier and not a QWidget, is to enable grabbing of windows
2132 that are not part of the application, window system frames, and so
2135 The grabWindow() function grabs pixels from the screen, not from
2136 the window, i.e. if there is another window partially or entirely
2137 over the one you grab, you get pixels from the overlying window,
2138 too. The mouse cursor is generally not grabbed.
2140 Note on X11 that if the given \a window doesn't have the same depth
2141 as the root window, and another window partially or entirely
2142 obscures the one you grab, you will \e not get pixels from the
2143 overlying window. The contents of the obscured areas in the
2144 pixmap will be undefined and uninitialized.
2146 On Windows Vista and above grabbing a layered window, which is
2147 created by setting the Qt::WA_TranslucentBackground attribute, will
2148 not work. Instead grabbing the desktop widget should work.
2150 \warning In general, grabbing an area outside the screen is not
2151 safe. This depends on the underlying window system.
2153 \sa grabWidget(), {Screenshot Example}
2159 QPixmapData* QPixmap::pixmapData() const
2162 QPixmapData* pm = data.data();
2163 return pm->runtimeData() ? pm->runtimeData() : pm;
2171 \enum QPixmap::HBitmapFormat
2173 \bold{Win32 only:} This enum defines how the conversion between \c
2174 HBITMAP and QPixmap is performed.
2176 \warning This enum is only available on Windows.
2178 \value NoAlpha The alpha channel is ignored and always treated as
2179 being set to fully opaque. This is preferred if the \c HBITMAP is
2180 used with standard GDI calls, such as \c BitBlt().
2182 \value PremultipliedAlpha The \c HBITMAP is treated as having an
2183 alpha channel and premultiplied colors. This is preferred if the
2184 \c HBITMAP is accessed through the \c AlphaBlend() GDI function.
2186 \value Alpha The \c HBITMAP is treated as having a plain alpha
2187 channel. This is the preferred format if the \c HBITMAP is going
2188 to be used as an application icon or systray icon.
2190 \sa fromWinHBITMAP(), toWinHBITMAP()
2193 /*! \fn HBITMAP QPixmap::toWinHBITMAP(HBitmapFormat format) const
2194 \bold{Win32 only:} Creates a \c HBITMAP equivalent to the QPixmap,
2195 based on the given \a format. Returns the \c HBITMAP handle.
2197 It is the caller's responsibility to free the \c HBITMAP data
2200 \warning This function is only available on Windows.
2202 \sa fromWinHBITMAP(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2205 /*! \fn QPixmap QPixmap::fromWinHBITMAP(HBITMAP bitmap, HBitmapFormat format)
2206 \bold{Win32 only:} Returns a QPixmap that is equivalent to the
2207 given \a bitmap. The conversion is based on the specified \a
2210 \warning This function is only available on Windows.
2212 \sa toWinHBITMAP(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2216 /*! \fn HICON QPixmap::toWinHICON() const
2219 \bold{Win32 only:} Creates a \c HICON equivalent to the QPixmap.
2220 Returns the \c HICON handle.
2222 It is the caller's responsibility to free the \c HICON data after use.
2224 \warning This function is only available on Windows.
2226 \sa fromWinHICON(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2229 /*! \fn QPixmap QPixmap::fromWinHICON(HICON icon)
2232 \bold{Win32 only:} Returns a QPixmap that is equivalent to the given
2235 \warning This function is only available on Windows.
2237 \sa toWinHICON(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2241 /*! \fn const QX11Info &QPixmap::x11Info() const
2242 \bold{X11 only:} Returns information about the configuration of
2243 the X display used by the screen to which the pixmap currently belongs.
2245 \warning This function is only available on X11.
2247 \sa {QPixmap#Pixmap Information}{Pixmap Information}
2250 /*! \fn Qt::HANDLE QPixmap::x11PictureHandle() const
2251 \bold{X11 only:} Returns the X11 Picture handle of the pixmap for
2254 This function will return 0 if XRender support is not compiled
2255 into Qt, if the XRender extension is not supported on the X11
2256 display, or if the handle could not be created. Use of this
2257 function is not portable.
2259 \warning This function is only available on X11.
2261 \sa {QPixmap#Pixmap Information}{Pixmap Information}
2264 /*! \fn int QPixmap::x11SetDefaultScreen(int screen)
2268 /*! \fn void QPixmap::x11SetScreen(int screen)
2272 /*! \fn QRgb* QPixmap::clut() const
2276 /*! \fn int QPixmap::numCols() const
2282 /*! \fn int QPixmap::colorCount() const
2287 /*! \fn const uchar* QPixmap::qwsBits() const
2292 /*! \fn int QPixmap::qwsBytesPerLine() const