1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
45 #include "qplatformpixmap_qpa.h"
46 #include "qimagepixmapcleanuphooks_p.h"
51 #include "qdatastream.h"
53 #include <private/qguiapplication_p.h>
56 #include "qfileinfo.h"
57 #include "qpixmapcache.h"
58 #include "qdatetime.h"
59 #include "qimagereader.h"
60 #include "qimagewriter.h"
61 #include "qpaintengine.h"
66 # include "qplatformintegration_qpa.h"
68 #include "qpixmap_raster_p.h"
69 #include "private/qhexstring_p.h"
73 static bool qt_pixmap_thread_test()
75 if (!QCoreApplication::instance()) {
76 qFatal("QPixmap: Must construct a QApplication before a QPaintDevice");
80 if (qApp->thread() != QThread::currentThread()) {
82 if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ThreadedPixmaps)) {
83 printf("Lighthouse plugin does not support threaded pixmaps!\n");
87 qWarning("QPixmap: It is not safe to use pixmaps outside the GUI thread");
94 void QPixmap::doInit(int w, int h, int type)
96 if ((w > 0 && h > 0) || type == QPlatformPixmap::BitmapType)
97 data = QPlatformPixmap::create(w, h, (QPlatformPixmap::PixelType) type);
103 Constructs a null pixmap.
111 (void) qt_pixmap_thread_test();
112 doInit(0, 0, QPlatformPixmap::PixmapType);
116 \fn QPixmap::QPixmap(int width, int height)
118 Constructs a pixmap with the given \a width and \a height. If
119 either \a width or \a height is zero, a null pixmap is
122 \warning This will create a QPixmap with uninitialized data. Call
123 fill() to fill the pixmap with an appropriate color before drawing
124 onto it with QPainter.
129 QPixmap::QPixmap(int w, int h)
132 if (!qt_pixmap_thread_test())
133 doInit(0, 0, QPlatformPixmap::PixmapType);
135 doInit(w, h, QPlatformPixmap::PixmapType);
141 Constructs a pixmap of the given \a size.
143 \warning This will create a QPixmap with uninitialized data. Call
144 fill() to fill the pixmap with an appropriate color before drawing
145 onto it with QPainter.
148 QPixmap::QPixmap(const QSize &size)
151 if (!qt_pixmap_thread_test())
152 doInit(0, 0, QPlatformPixmap::PixmapType);
154 doInit(size.width(), size.height(), QPlatformPixmap::PixmapType);
160 QPixmap::QPixmap(const QSize &s, int type)
162 if (!qt_pixmap_thread_test())
163 doInit(0, 0, static_cast<QPlatformPixmap::PixelType>(type));
165 doInit(s.width(), s.height(), static_cast<QPlatformPixmap::PixelType>(type));
171 QPixmap::QPixmap(QPlatformPixmap *d)
172 : QPaintDevice(), data(d)
177 Constructs a pixmap from the file with the given \a fileName. If the
178 file does not exist or is of an unknown format, the pixmap becomes a
181 The loader attempts to read the pixmap using the specified \a
182 format. If the \a format is not specified (which is the default),
183 the loader probes the file for a header to guess the file format.
185 The file name can either refer to an actual file on disk or to
186 one of the application's embedded resources. See the
187 \l{resources.html}{Resource System} overview for details on how
188 to embed images and other resource files in the application's
191 If the image needs to be modified to fit in a lower-resolution
192 result (e.g. converting from 32-bit to 8-bit), use the \a
193 flags to control the conversion.
195 The \a fileName, \a format and \a flags parameters are
196 passed on to load(). This means that the data in \a fileName is
197 not compiled into the binary. If \a fileName contains a relative
198 path (e.g. the filename only) the relevant file must be found
199 relative to the runtime working directory.
201 \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
205 QPixmap::QPixmap(const QString& fileName, const char *format, Qt::ImageConversionFlags flags)
208 doInit(0, 0, QPlatformPixmap::PixmapType);
209 if (!qt_pixmap_thread_test())
212 load(fileName, format, flags);
216 Constructs a pixmap that is a copy of the given \a pixmap.
221 QPixmap::QPixmap(const QPixmap &pixmap)
224 if (!qt_pixmap_thread_test()) {
225 doInit(0, 0, QPlatformPixmap::PixmapType);
228 if (pixmap.paintingActive()) { // make a deep copy
229 operator=(pixmap.copy());
236 Constructs a pixmap from the given \a xpm data, which must be a
239 Errors are silently ignored.
241 Note that it's possible to squeeze the XPM variable a little bit
242 by using an unusual declaration:
244 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 0
246 The extra \c const makes the entire definition read-only, which is
247 slightly more efficient (for example, when the code is in a shared
248 library) and ROMable when the application is to be stored in ROM.
250 #ifndef QT_NO_IMAGEFORMAT_XPM
251 QPixmap::QPixmap(const char * const xpm[])
254 doInit(0, 0, QPlatformPixmap::PixmapType);
259 if (!image.isNull()) {
260 if (data && data->pixelType() == QPlatformPixmap::BitmapType)
261 *this = QBitmap::fromImage(image);
263 *this = fromImage(image);
275 Q_ASSERT(!data || data->ref.load() >= 1); // Catch if ref-counting changes again
281 int QPixmap::devType() const
283 return QInternal::Pixmap;
287 \fn QPixmap QPixmap::copy(int x, int y, int width, int height) const
290 Returns a deep copy of the subset of the pixmap that is specified
291 by the rectangle QRect( \a x, \a y, \a width, \a height).
295 \fn QPixmap QPixmap::copy(const QRect &rectangle) const
297 Returns a deep copy of the subset of the pixmap that is specified
298 by the given \a rectangle. For more information on deep copies,
299 see the \l {Implicit Data Sharing} documentation.
301 If the given \a rectangle is empty, the whole image is copied.
303 \sa operator=(), QPixmap(), {QPixmap#Pixmap
304 Transformations}{Pixmap Transformations}
306 QPixmap QPixmap::copy(const QRect &rect) const
311 QRect r(0, 0, width(), height());
313 r = r.intersected(rect);
315 QPlatformPixmap *d = data->createCompatiblePlatformPixmap();
316 d->copy(data.data(), r);
321 \fn QPixmap::scroll(int dx, int dy, int x, int y, int width, int height, QRegion *exposed)
324 This convenience function is equivalent to calling QPixmap::scroll(\a dx,
325 \a dy, QRect(\a x, \a y, \a width, \a height), \a exposed).
327 \sa QWidget::scroll(), QGraphicsItem::scroll()
333 Scrolls the area \a rect of this pixmap by (\a dx, \a dy). The exposed
334 region is left unchanged. You can optionally pass a pointer to an empty
335 QRegion to get the region that is \a exposed by the scroll operation.
337 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 2
339 You cannot scroll while there is an active painter on the pixmap.
341 \sa QWidget::scroll(), QGraphicsItem::scroll()
343 void QPixmap::scroll(int dx, int dy, const QRect &rect, QRegion *exposed)
345 if (isNull() || (dx == 0 && dy == 0))
347 QRect dest = rect & this->rect();
348 QRect src = dest.translated(-dx, -dy) & dest;
357 if (!data->scroll(dx, dy, src)) {
360 QPainter painter(&pix);
361 painter.setCompositionMode(QPainter::CompositionMode_Source);
362 painter.drawPixmap(src.translated(dx, dy), *this, src);
369 *exposed -= src.translated(dx, dy);
374 Assigns the given \a pixmap to this pixmap and returns a reference
377 \sa copy(), QPixmap()
380 QPixmap &QPixmap::operator=(const QPixmap &pixmap)
382 if (paintingActive()) {
383 qWarning("QPixmap::operator=: Cannot assign to pixmap during painting");
386 if (pixmap.paintingActive()) { // make a deep copy
387 *this = pixmap.copy();
395 \fn void QPixmap::swap(QPixmap &other)
398 Swaps pixmap \a other with this pixmap. This operation is very
399 fast and never fails.
403 Returns the pixmap as a QVariant.
405 QPixmap::operator QVariant() const
407 return QVariant(QVariant::Pixmap, this);
411 \fn bool QPixmap::operator!() const
413 Returns true if this is a null pixmap; otherwise returns false.
419 Converts the pixmap to a QImage. Returns a null image if the
422 If the pixmap has 1-bit depth, the returned image will also be 1
423 bit deep. Images with more bits will be returned in a format
424 closely represents the underlying system. Usually this will be
425 QImage::Format_ARGB32_Premultiplied for pixmaps with an alpha and
426 QImage::Format_RGB32 or QImage::Format_RGB16 for pixmaps without
429 Note that for the moment, alpha masks on monochrome images are
432 \sa fromImage(), {QImage#Image Formats}{Image Formats}
434 QImage QPixmap::toImage() const
439 return data->toImage();
443 \fn QMatrix QPixmap::trueMatrix(const QTransform &matrix, int width, int height)
445 Returns the actual matrix used for transforming a pixmap with the
446 given \a width, \a height and \a matrix.
448 When transforming a pixmap using the transformed() function, the
449 transformation matrix is internally adjusted to compensate for
450 unwanted translation, i.e. transformed() returns the smallest
451 pixmap containing all transformed points of the original
452 pixmap. This function returns the modified matrix, which maps
453 points correctly from the original pixmap into the new pixmap.
455 \sa transformed(), {QPixmap#Pixmap Transformations}{Pixmap
458 QTransform QPixmap::trueMatrix(const QTransform &m, int w, int h)
460 return QImage::trueMatrix(m, w, h);
466 This convenience function loads the matrix \a m into a
467 QTransform and calls the overloaded function with the
468 QTransform and the width \a w and the height \a h.
470 QMatrix QPixmap::trueMatrix(const QMatrix &m, int w, int h)
472 return trueMatrix(QTransform(m), w, h).toAffine();
477 \fn bool QPixmap::isQBitmap() const
479 Returns true if this is a QBitmap; otherwise returns false.
482 bool QPixmap::isQBitmap() const
484 return data->type == QPlatformPixmap::BitmapType;
488 \fn bool QPixmap::isNull() const
490 Returns true if this is a null pixmap; otherwise returns false.
492 A null pixmap has zero width, zero height and no contents. You
493 cannot draw in a null pixmap.
495 bool QPixmap::isNull() const
497 return !data || data->isNull();
501 \fn int QPixmap::width() const
503 Returns the width of the pixmap.
505 \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
507 int QPixmap::width() const
509 return data ? data->width() : 0;
513 \fn int QPixmap::height() const
515 Returns the height of the pixmap.
517 \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
519 int QPixmap::height() const
521 return data ? data->height() : 0;
525 \fn QSize QPixmap::size() const
527 Returns the size of the pixmap.
529 \sa width(), height(), {QPixmap#Pixmap Information}{Pixmap
532 QSize QPixmap::size() const
534 return data ? QSize(data->width(), data->height()) : QSize(0, 0);
538 \fn QRect QPixmap::rect() const
540 Returns the pixmap's enclosing rectangle.
542 \sa {QPixmap#Pixmap Information}{Pixmap Information}
544 QRect QPixmap::rect() const
546 return data ? QRect(0, 0, data->width(), data->height()) : QRect();
550 \fn int QPixmap::depth() const
552 Returns the depth of the pixmap.
554 The pixmap depth is also called bits per pixel (bpp) or bit planes
555 of a pixmap. A null pixmap has depth 0.
557 \sa defaultDepth(), {QPixmap#Pixmap Information}{Pixmap
560 int QPixmap::depth() const
562 return data ? data->depth() : 0;
568 This function merges the \a mask with the pixmap's alpha channel. A pixel
569 value of 1 on the mask means the pixmap's pixel is unchanged; a value of 0
570 means the pixel is transparent. The mask must have the same size as this
573 Setting a null mask resets the mask, leaving the previously transparent
574 pixels black. The effect of this function is undefined when the pixmap is
577 \warning This is potentially an expensive operation.
579 \sa mask(), {QPixmap#Pixmap Transformations}{Pixmap Transformations},
582 void QPixmap::setMask(const QBitmap &mask)
584 if (paintingActive()) {
585 qWarning("QPixmap::setMask: Cannot set mask while pixmap is being painted on");
589 if (!mask.isNull() && mask.size() != size()) {
590 qWarning("QPixmap::setMask() mask size differs from pixmap size");
597 if (static_cast<const QPixmap &>(mask).data == data) // trying to selfmask
602 QImage image = data->toImage();
603 if (mask.size().isEmpty()) {
604 if (image.depth() != 1) { // hw: ????
605 image = image.convertToFormat(QImage::Format_RGB32);
608 const int w = image.width();
609 const int h = image.height();
611 switch (image.depth()) {
613 const QImage imageMask = mask.toImage().convertToFormat(image.format());
614 for (int y = 0; y < h; ++y) {
615 const uchar *mscan = imageMask.scanLine(y);
616 uchar *tscan = image.scanLine(y);
617 int bytesPerLine = image.bytesPerLine();
618 for (int i = 0; i < bytesPerLine; ++i)
619 tscan[i] &= mscan[i];
624 const QImage imageMask = mask.toImage().convertToFormat(QImage::Format_MonoLSB);
625 image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied);
626 for (int y = 0; y < h; ++y) {
627 const uchar *mscan = imageMask.scanLine(y);
628 QRgb *tscan = (QRgb *)image.scanLine(y);
629 for (int x = 0; x < w; ++x) {
630 if (!(mscan[x>>3] & (1 << (x&7))))
638 data->fromImage(image, Qt::AutoColor);
641 #ifndef QT_NO_IMAGE_HEURISTIC_MASK
643 Creates and returns a heuristic mask for this pixmap.
645 The function works by selecting a color from one of the corners
646 and then chipping away pixels of that color, starting at all the
647 edges. If \a clipTight is true (the default) the mask is just
648 large enough to cover the pixels; otherwise, the mask is larger
649 than the data pixels.
651 The mask may not be perfect but it should be reasonable, so you
652 can do things such as the following:
654 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 1
656 This function is slow because it involves converting to/from a
657 QImage, and non-trivial computations.
659 \sa QImage::createHeuristicMask(), createMaskFromColor()
661 QBitmap QPixmap::createHeuristicMask(bool clipTight) const
663 QBitmap m = QBitmap::fromImage(toImage().createHeuristicMask(clipTight));
669 Creates and returns a mask for this pixmap based on the given \a
670 maskColor. If the \a mode is Qt::MaskInColor, all pixels matching the
671 maskColor will be transparent. If \a mode is Qt::MaskOutColor, all pixels
672 matching the maskColor will be opaque.
674 This function is slow because it involves converting to/from a
677 \sa createHeuristicMask(), QImage::createMaskFromColor()
679 QBitmap QPixmap::createMaskFromColor(const QColor &maskColor, Qt::MaskMode mode) const
681 QImage image = toImage().convertToFormat(QImage::Format_ARGB32);
682 return QBitmap::fromImage(image.createMaskFromColor(maskColor.rgba(), mode));
686 Loads a pixmap from the file with the given \a fileName. Returns
687 true if the pixmap was successfully loaded; otherwise returns
690 The loader attempts to read the pixmap using the specified \a
691 format. If the \a format is not specified (which is the default),
692 the loader probes the file for a header to guess the file format.
694 The file name can either refer to an actual file on disk or to one
695 of the application's embedded resources. See the
696 \l{resources.html}{Resource System} overview for details on how to
697 embed pixmaps and other resource files in the application's
700 If the data needs to be modified to fit in a lower-resolution
701 result (e.g. converting from 32-bit to 8-bit), use the \a flags to
702 control the conversion.
704 Note that QPixmaps are automatically added to the QPixmapCache
705 when loaded from a file; the key used is internal and can not
708 \sa loadFromData(), {QPixmap#Reading and Writing Image
709 Files}{Reading and Writing Image Files}
712 bool QPixmap::load(const QString &fileName, const char *format, Qt::ImageConversionFlags flags)
714 if (fileName.isEmpty())
717 QFileInfo info(fileName);
718 QString key = QLatin1String("qt_pixmap")
719 % info.absoluteFilePath()
720 % HexString<uint>(info.lastModified().toTime_t())
721 % HexString<quint64>(info.size())
722 % HexString<uint>(data ? data->pixelType() : QPlatformPixmap::PixmapType);
724 // Note: If no extension is provided, we try to match the
725 // file against known plugin extensions
726 if (!info.completeSuffix().isEmpty() && !info.exists())
729 if (QPixmapCache::find(key, *this))
732 QScopedPointer<QPlatformPixmap> tmp(QPlatformPixmap::create(0, 0, data ? data->type : QPlatformPixmap::PixmapType));
733 if (tmp->fromFile(fileName, format, flags)) {
735 QPixmapCache::insert(key, *this);
743 \fn bool QPixmap::loadFromData(const uchar *data, uint len, const char *format, Qt::ImageConversionFlags flags)
745 Loads a pixmap from the \a len first bytes of the given binary \a
746 data. Returns true if the pixmap was loaded successfully;
747 otherwise returns false.
749 The loader attempts to read the pixmap using the specified \a
750 format. If the \a format is not specified (which is the default),
751 the loader probes the file for a header to guess the file format.
753 If the data needs to be modified to fit in a lower-resolution
754 result (e.g. converting from 32-bit to 8-bit), use the \a flags to
755 control the conversion.
757 \sa load(), {QPixmap#Reading and Writing Image Files}{Reading and
761 bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, Qt::ImageConversionFlags flags)
763 if (len == 0 || buf == 0)
767 data = QPlatformPixmap::create(0, 0, QPlatformPixmap::PixmapType);
769 return data->fromData(buf, len, format, flags);
773 \fn bool QPixmap::loadFromData(const QByteArray &data, const char *format, Qt::ImageConversionFlags flags)
777 Loads a pixmap from the binary \a data using the specified \a
778 format and conversion \a flags.
783 Saves the pixmap to the file with the given \a fileName using the
784 specified image file \a format and \a quality factor. Returns true
785 if successful; otherwise returns false.
787 The \a quality factor must be in the range [0,100] or -1. Specify
788 0 to obtain small compressed files, 100 for large uncompressed
789 files, and -1 to use the default settings.
791 If \a format is 0, an image format will be chosen from \a fileName's
794 \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
798 bool QPixmap::save(const QString &fileName, const char *format, int quality) const
801 return false; // nothing to save
802 QImageWriter writer(fileName, format);
803 return doImageIO(&writer, quality);
809 This function writes a QPixmap to the given \a device using the
810 specified image file \a format and \a quality factor. This can be
811 used, for example, to save a pixmap directly into a QByteArray:
813 \snippet doc/src/snippets/image/image.cpp 1
816 bool QPixmap::save(QIODevice* device, const char* format, int quality) const
819 return false; // nothing to save
820 QImageWriter writer(device, format);
821 return doImageIO(&writer, quality);
826 bool QPixmap::doImageIO(QImageWriter *writer, int quality) const
828 if (quality > 100 || quality < -1)
829 qWarning("QPixmap::save: quality out of range [-1,100]");
831 writer->setQuality(qMin(quality,100));
832 return writer->write(toImage());
836 \fn void QPixmap::fill(const QPaintDevice *device, int x, int y)
841 Fills the pixmap with the \a device's background color or pixmap.
842 The given point, (\a x, \a y), defines an offset in widget
843 coordinates to which the pixmap's top-left pixel will be mapped
847 void QPixmap::fill(const QPaintDevice *, const QPoint &)
849 qWarning() << "QPixmap::fill(const QPaintDevice *device, const QPoint &offset) is deprecated, ignored";
854 Fills the pixmap with the given \a color.
856 The effect of this function is undefined when the pixmap is
859 \sa {QPixmap#Pixmap Transformations}{Pixmap Transformations}
862 void QPixmap::fill(const QColor &color)
867 // Some people are probably already calling fill while a painter is active, so to not break
868 // their programs, only print a warning and return when the fill operation could cause a crash.
869 if (paintingActive() && (color.alpha() != 255) && !hasAlphaChannel()) {
870 qWarning("QPixmap::fill: Cannot fill while pixmap is being painted on");
874 if (data->ref.load() == 1) {
875 // detach() will also remove this pixmap from caches, so
876 // it has to be called even when ref == 1.
879 // Don't bother to make a copy of the data object, since
880 // it will be filled with new pixel data anyway.
881 QPlatformPixmap *d = data->createCompatiblePlatformPixmap();
882 d->resize(data->width(), data->height());
888 /*! \fn int QPixmap::serialNumber() const
890 Returns a number that identifies the contents of this QPixmap
891 object. Distinct QPixmap objects can only have the same serial
892 number if they refer to the same contents (but they don't have
895 Use cacheKey() instead.
897 \warning The serial number doesn't necessarily change when
898 the pixmap is altered. This means that it may be dangerous to use
899 it as a cache key. For caching pixmaps, we recommend using the
900 QPixmapCache class whenever possible.
904 Returns a number that identifies this QPixmap. Distinct QPixmap
905 objects can only have the same cache key if they refer to the same
908 The cacheKey() will change when the pixmap is altered.
910 qint64 QPixmap::cacheKey() const
916 return data->cacheKey();
920 static void sendResizeEvents(QWidget *target)
922 QResizeEvent e(target->size(), QSize());
923 QApplication::sendEvent(target, &e);
925 const QObjectList children = target->children();
926 for (int i = 0; i < children.size(); ++i) {
927 QWidget *child = static_cast<QWidget*>(children.at(i));
928 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
929 sendResizeEvents(child);
934 QPixmap QPixmap::grabWidget(QObject *widget, const QRect &rectangle)
937 qWarning("QPixmap::grabWidget is deprecated, use QWidget::grab() instead");
940 QMetaObject::invokeMethod(widget, "grab", Qt::DirectConnection,
941 Q_RETURN_ARG(QPixmap, pixmap),
942 Q_ARG(QRect, rectangle));
946 /*****************************************************************************
947 QPixmap stream functions
948 *****************************************************************************/
949 #if !defined(QT_NO_DATASTREAM)
953 Writes the given \a pixmap to the given \a stream as a PNG
954 image. Note that writing the stream to a file will not produce a
957 \sa QPixmap::save(), {Serializing Qt Data Types}
960 QDataStream &operator<<(QDataStream &stream, const QPixmap &pixmap)
962 return stream << pixmap.toImage();
968 Reads an image from the given \a stream into the given \a pixmap.
970 \sa QPixmap::load(), {Serializing Qt Data Types}
973 QDataStream &operator>>(QDataStream &stream, QPixmap &pixmap)
978 if (image.isNull()) {
980 } else if (image.depth() == 1) {
981 pixmap = QBitmap::fromImage(image);
983 pixmap = QPixmap::fromImage(image);
988 #endif // QT_NO_DATASTREAM
994 bool QPixmap::isDetached() const
996 return data && data->ref.load() == 1;
1000 Replaces this pixmap's data with the given \a image using the
1001 specified \a flags to control the conversion. The \a flags
1002 argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}.
1003 Passing 0 for \a flags sets all the default options. Returns true
1004 if the result is that this pixmap is not null.
1006 Note: this function was part of Qt 3 support in Qt 4.6 and earlier.
1007 It has been promoted to official API status in 4.7 to support updating
1008 the pixmap's image without creating a new QPixmap as fromImage() would.
1013 bool QPixmap::convertFromImage(const QImage &image, Qt::ImageConversionFlags flags)
1015 if (image.isNull() || !data)
1016 *this = QPixmap::fromImage(image, flags);
1018 data->fromImage(image, flags);
1023 \fn QPixmap QPixmap::scaled(int width, int height,
1024 Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode
1025 transformMode) const
1029 Returns a copy of the pixmap scaled to a rectangle with the given
1030 \a width and \a height according to the given \a aspectRatioMode and
1033 If either the \a width or the \a height is zero or negative, this
1034 function returns a null pixmap.
1038 \fn QPixmap QPixmap::scaled(const QSize &size, Qt::AspectRatioMode
1039 aspectRatioMode, Qt::TransformationMode transformMode) const
1041 Scales the pixmap to the given \a size, using the aspect ratio and
1042 transformation modes specified by \a aspectRatioMode and \a
1045 \image qimage-scaling.png
1048 \li If \a aspectRatioMode is Qt::IgnoreAspectRatio, the pixmap
1049 is scaled to \a size.
1050 \li If \a aspectRatioMode is Qt::KeepAspectRatio, the pixmap is
1051 scaled to a rectangle as large as possible inside \a size, preserving the aspect ratio.
1052 \li If \a aspectRatioMode is Qt::KeepAspectRatioByExpanding,
1053 the pixmap is scaled to a rectangle as small as possible
1054 outside \a size, preserving the aspect ratio.
1057 If the given \a size is empty, this function returns a null
1061 In some cases it can be more beneficial to draw the pixmap to a
1062 painter with a scale set rather than scaling the pixmap. This is
1063 the case when the painter is for instance based on OpenGL or when
1064 the scale factor changes rapidly.
1066 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1070 QPixmap QPixmap::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::TransformationMode mode) const
1073 qWarning("QPixmap::scaled: Pixmap is a null pixmap");
1079 QSize newSize = size();
1080 newSize.scale(s, aspectMode);
1081 newSize.rwidth() = qMax(newSize.width(), 1);
1082 newSize.rheight() = qMax(newSize.height(), 1);
1083 if (newSize == size())
1086 QTransform wm = QTransform::fromScale((qreal)newSize.width() / width(),
1087 (qreal)newSize.height() / height());
1088 QPixmap pix = transformed(wm, mode);
1093 \fn QPixmap QPixmap::scaledToWidth(int width, Qt::TransformationMode
1096 Returns a scaled copy of the image. The returned image is scaled
1097 to the given \a width using the specified transformation \a mode.
1098 The height of the pixmap is automatically calculated so that the
1099 aspect ratio of the pixmap is preserved.
1101 If \a width is 0 or negative, a null pixmap is returned.
1103 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1106 QPixmap QPixmap::scaledToWidth(int w, Qt::TransformationMode mode) const
1109 qWarning("QPixmap::scaleWidth: Pixmap is a null pixmap");
1115 qreal factor = (qreal) w / width();
1116 QTransform wm = QTransform::fromScale(factor, factor);
1117 return transformed(wm, mode);
1121 \fn QPixmap QPixmap::scaledToHeight(int height,
1122 Qt::TransformationMode mode) const
1124 Returns a scaled copy of the image. The returned image is scaled
1125 to the given \a height using the specified transformation \a mode.
1126 The width of the pixmap is automatically calculated so that the
1127 aspect ratio of the pixmap is preserved.
1129 If \a height is 0 or negative, a null pixmap is returned.
1131 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1134 QPixmap QPixmap::scaledToHeight(int h, Qt::TransformationMode mode) const
1137 qWarning("QPixmap::scaleHeight: Pixmap is a null pixmap");
1143 qreal factor = (qreal) h / height();
1144 QTransform wm = QTransform::fromScale(factor, factor);
1145 return transformed(wm, mode);
1149 Returns a copy of the pixmap that is transformed using the given
1150 transformation \a transform and transformation \a mode. The original
1151 pixmap is not changed.
1153 The transformation \a transform is internally adjusted to compensate
1154 for unwanted translation; i.e. the pixmap produced is the smallest
1155 pixmap that contains all the transformed points of the original
1156 pixmap. Use the trueMatrix() function to retrieve the actual
1157 matrix used for transforming the pixmap.
1159 This function is slow because it involves transformation to a
1160 QImage, non-trivial computations and a transformation back to a
1163 \sa trueMatrix(), {QPixmap#Pixmap Transformations}{Pixmap
1166 QPixmap QPixmap::transformed(const QTransform &transform,
1167 Qt::TransformationMode mode) const
1169 if (isNull() || transform.type() <= QTransform::TxTranslate)
1172 return data->transformed(transform, mode);
1178 This convenience function loads the \a matrix into a
1179 QTransform and calls the overloaded function.
1181 QPixmap QPixmap::transformed(const QMatrix &matrix, Qt::TransformationMode mode) const
1183 return transformed(QTransform(matrix), mode);
1196 \brief The QPixmap class is an off-screen image representation
1197 that can be used as a paint device.
1203 Qt provides four classes for handling image data: QImage, QPixmap,
1204 QBitmap and QPicture. QImage is designed and optimized for I/O,
1205 and for direct pixel access and manipulation, while QPixmap is
1206 designed and optimized for showing images on screen. QBitmap is
1207 only a convenience class that inherits QPixmap, ensuring a depth
1208 of 1. The isQBitmap() function returns true if a QPixmap object is
1209 really a bitmap, otherwise returns false. Finally, the QPicture class
1210 is a paint device that records and replays QPainter commands.
1212 A QPixmap can easily be displayed on the screen using QLabel or
1213 one of QAbstractButton's subclasses (such as QPushButton and
1214 QToolButton). QLabel has a pixmap property, whereas
1215 QAbstractButton has an icon property.
1217 In addition to the ordinary constructors, a QPixmap can be
1218 constructed using the static grabWidget() and grabWindow()
1219 functions which creates a QPixmap and paints the given widget, or
1222 QPixmap objects can be passed around by value since the QPixmap
1223 class uses implicit data sharing. For more information, see the \l
1224 {Implicit Data Sharing} documentation. QPixmap objects can also be
1227 Note that the pixel data in a pixmap is internal and is managed by
1228 the underlying window system. Because QPixmap is a QPaintDevice
1229 subclass, QPainter can be used to draw directly onto pixmaps.
1230 Pixels can only be accessed through QPainter functions or by
1231 converting the QPixmap to a QImage. However, the fill() function
1232 is available for initializing the entire pixmap with a given color.
1234 There are functions to convert between QImage and
1235 QPixmap. Typically, the QImage class is used to load an image
1236 file, optionally manipulating the image data, before the QImage
1237 object is converted into a QPixmap to be shown on
1238 screen. Alternatively, if no manipulation is desired, the image
1239 file can be loaded directly into a QPixmap. On Windows, the
1240 QPixmap class also supports conversion between \c HBITMAP and
1243 QPixmap provides a collection of functions that can be used to
1244 obtain a variety of information about the pixmap. In addition,
1245 there are several functions that enables transformation of the
1250 \section1 Reading and Writing Image Files
1252 QPixmap provides several ways of reading an image file: The file
1253 can be loaded when constructing the QPixmap object, or by using
1254 the load() or loadFromData() functions later on. When loading an
1255 image, the file name can either refer to an actual file on disk or
1256 to one of the application's embedded resources. See \l{The Qt
1257 Resource System} overview for details on how to embed images and
1258 other resource files in the application's executable.
1260 Simply call the save() function to save a QPixmap object.
1262 The complete list of supported file formats are available through
1263 the QImageReader::supportedImageFormats() and
1264 QImageWriter::supportedImageFormats() functions. New file formats
1265 can be added as plugins. By default, Qt supports the following
1269 \header \li Format \li Description \li Qt's support
1270 \row \li BMP \li Windows Bitmap \li Read/write
1271 \row \li GIF \li Graphic Interchange Format (optional) \li Read
1272 \row \li JPG \li Joint Photographic Experts Group \li Read/write
1273 \row \li JPEG \li Joint Photographic Experts Group \li Read/write
1274 \row \li PNG \li Portable Network Graphics \li Read/write
1275 \row \li PBM \li Portable Bitmap \li Read
1276 \row \li PGM \li Portable Graymap \li Read
1277 \row \li PPM \li Portable Pixmap \li Read/write
1278 \row \li XBM \li X11 Bitmap \li Read/write
1279 \row \li XPM \li X11 Pixmap \li Read/write
1282 \section1 Pixmap Information
1284 QPixmap provides a collection of functions that can be used to
1285 obtain a variety of information about the pixmap:
1289 \li \li Available Functions
1293 The size(), width() and height() functions provide information
1294 about the pixmap's size. The rect() function returns the image's
1295 enclosing rectangle.
1301 The hasAlphaChannel() returns true if the pixmap has a format that
1302 respects the alpha channel, otherwise returns false. The hasAlpha(),
1303 setMask() and mask() functions are legacy and should not be used.
1304 They are potentially very slow.
1306 The createHeuristicMask() function creates and returns a 1-bpp
1307 heuristic mask (i.e. a QBitmap) for this pixmap. It works by
1308 selecting a color from one of the corners and then chipping away
1309 pixels of that color, starting at all the edges. The
1310 createMaskFromColor() function creates and returns a mask (i.e. a
1311 QBitmap) for the pixmap based on a given color.
1314 \li Low-level information
1317 The depth() function returns the depth of the pixmap. The
1318 defaultDepth() function returns the default depth, i.e. the depth
1319 used by the application on the given screen.
1321 The cacheKey() function returns a number that uniquely
1322 identifies the contents of the QPixmap object.
1324 The x11Info() function returns information about the configuration
1325 of the X display used by the screen to which the pixmap currently
1326 belongs. The x11PictureHandle() function returns the X11 Picture
1327 handle of the pixmap for XRender support. Note that the two latter
1328 functions are only available on x11.
1332 \section1 Pixmap Conversion
1334 A QPixmap object can be converted into a QImage using the
1335 toImage() function. Likewise, a QImage can be converted into a
1336 QPixmap using the fromImage(). If this is too expensive an
1337 operation, you can use QBitmap::fromImage() instead.
1339 In addition, on Windows, the QPixmap class supports conversion to
1340 and from HBITMAP: the toWinHBITMAP() function creates a HBITMAP
1341 equivalent to the QPixmap, based on the given HBitmapFormat, and
1342 returns the HBITMAP handle. The fromWinHBITMAP() function returns
1343 a QPixmap that is equivalent to the given bitmap which has the
1344 specified format. The QPixmap class also supports conversion to
1345 and from HICON: the toWinHICON() function creates a HICON equivalent
1346 to the QPixmap, and returns the HICON handle. The fromWinHICON()
1347 function returns a QPixmap that is equivalent to the given icon.
1349 \section1 Pixmap Transformations
1351 QPixmap supports a number of functions for creating a new pixmap
1352 that is a transformed version of the original:
1354 The scaled(), scaledToWidth() and scaledToHeight() functions
1355 return scaled copies of the pixmap, while the copy() function
1356 creates a QPixmap that is a plain copy of the original one.
1358 The transformed() function returns a copy of the pixmap that is
1359 transformed with the given transformation matrix and
1360 transformation mode: Internally, the transformation matrix is
1361 adjusted to compensate for unwanted translation,
1362 i.e. transformed() returns the smallest pixmap containing all
1363 transformed points of the original pixmap. The static trueMatrix()
1364 function returns the actual matrix used for transforming the
1367 \note When using the native X11 graphics system, the pixmap
1368 becomes invalid when the QApplication instance is destroyed.
1370 \sa QBitmap, QImage, QImageReader, QImageWriter
1375 \typedef QPixmap::DataPtr
1380 \fn DataPtr &QPixmap::data_ptr()
1385 Returns true if this pixmap has an alpha channel, \e or has a
1386 mask, otherwise returns false.
1388 \sa hasAlphaChannel(), mask()
1390 bool QPixmap::hasAlpha() const
1392 return data && data->hasAlphaChannel();
1396 Returns true if the pixmap has a format that respects the alpha
1397 channel, otherwise returns false.
1401 bool QPixmap::hasAlphaChannel() const
1403 return data && data->hasAlphaChannel();
1409 int QPixmap::metric(PaintDeviceMetric metric) const
1411 return data ? data->metric(metric) : 0;
1417 QPaintEngine *QPixmap::paintEngine() const
1419 return data ? data->paintEngine() : 0;
1423 \fn QBitmap QPixmap::mask() const
1425 Extracts a bitmap mask from the pixmap's alpha channel.
1427 \warning This is potentially an expensive operation. The mask of
1428 the pixmap is extracted dynamically from the pixeldata.
1430 \sa setMask(), {QPixmap#Pixmap Information}{Pixmap Information}
1432 QBitmap QPixmap::mask() const
1434 if (!data || !hasAlphaChannel())
1437 const QImage img = toImage();
1438 const QImage image = (img.depth() < 32 ? img.convertToFormat(QImage::Format_ARGB32_Premultiplied) : img);
1439 const int w = image.width();
1440 const int h = image.height();
1442 QImage mask(w, h, QImage::Format_MonoLSB);
1443 if (mask.isNull()) // allocation failed
1446 mask.setColorCount(2);
1447 mask.setColor(0, QColor(Qt::color0).rgba());
1448 mask.setColor(1, QColor(Qt::color1).rgba());
1450 const int bpl = mask.bytesPerLine();
1452 for (int y = 0; y < h; ++y) {
1453 const QRgb *src = reinterpret_cast<const QRgb*>(image.scanLine(y));
1454 uchar *dest = mask.scanLine(y);
1455 memset(dest, 0, bpl);
1456 for (int x = 0; x < w; ++x) {
1457 if (qAlpha(*src) > 0)
1458 dest[x >> 3] |= (1 << (x & 7));
1463 return QBitmap::fromImage(mask);
1467 Returns the default pixmap depth used by the application.
1469 On all platforms the depth of the primary screen will be returned.
1471 \sa depth(), QColormap::depth(), {QPixmap#Pixmap Information}{Pixmap Information}
1474 int QPixmap::defaultDepth()
1476 return QGuiApplication::primaryScreen()->depth();
1480 Detaches the pixmap from shared pixmap data.
1482 A pixmap is automatically detached by Qt whenever its contents are
1483 about to change. This is done in almost all QPixmap member
1484 functions that modify the pixmap (fill(), fromImage(),
1485 load(), etc.), and in QPainter::begin() on a pixmap.
1487 There are two exceptions in which detach() must be called
1488 explicitly, that is when calling the handle() or the
1489 x11PictureHandle() function (only available on X11). Otherwise,
1490 any modifications done using system calls, will be performed on
1493 The detach() function returns immediately if there is just a
1494 single reference or if the pixmap has not been initialized yet.
1496 void QPixmap::detach()
1501 // QPixmap.data member may be QRuntimePlatformPixmap so use handle() function to get
1502 // the actual underlaying runtime pixmap data.
1503 QPlatformPixmap *pd = handle();
1504 QPlatformPixmap::ClassId id = pd->classId();
1505 if (id == QPlatformPixmap::RasterClass) {
1506 QRasterPlatformPixmap *rasterData = static_cast<QRasterPlatformPixmap*>(pd);
1507 rasterData->image.detach();
1510 if (data->is_cached && data->ref.load() == 1)
1511 QImagePixmapCleanupHooks::executePlatformPixmapModificationHooks(data.data());
1513 if (data->ref.load() != 1) {
1520 \fn QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1522 Converts the given \a image to a pixmap using the specified \a
1523 flags to control the conversion. The \a flags argument is a
1524 bitwise-OR of the \l{Qt::ImageConversionFlags}. Passing 0 for \a
1525 flags sets all the default options.
1527 In case of monochrome and 8-bit images, the image is first
1528 converted to a 32-bit pixmap and then filled with the colors in
1529 the color table. If this is too expensive an operation, you can
1530 use QBitmap::fromImage() instead.
1532 \sa fromImageReader(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
1534 QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1539 QScopedPointer<QPlatformPixmap> data(QGuiApplicationPrivate::platformIntegration()->createPlatformPixmap(QPlatformPixmap::PixmapType));
1540 data->fromImage(image, flags);
1541 return QPixmap(data.take());
1545 \fn QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags)
1547 Create a QPixmap from an image read directly from an \a imageReader.
1548 The \a flags argument is a bitwise-OR of the \l{Qt::ImageConversionFlags}.
1549 Passing 0 for \a flags sets all the default options.
1551 On some systems, reading an image directly to QPixmap can use less memory than
1552 reading a QImage to convert it to QPixmap.
1554 \sa fromImage(), toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
1556 QPixmap QPixmap::fromImageReader(QImageReader *imageReader, Qt::ImageConversionFlags flags)
1558 QScopedPointer<QPlatformPixmap> data(QGuiApplicationPrivate::platformIntegration()->createPlatformPixmap(QPlatformPixmap::PixmapType));
1559 data->fromImageReader(imageReader, flags);
1560 return QPixmap(data.take());
1564 \fn QPixmap QPixmap::grabWindow(WId window, int x, int y, int
1567 Creates and returns a pixmap constructed by grabbing the contents
1568 of the given \a window restricted by QRect(\a x, \a y, \a width,
1571 The arguments (\a{x}, \a{y}) specify the offset in the window,
1572 whereas (\a{width}, \a{height}) specify the area to be copied. If
1573 \a width is negative, the function copies everything to the right
1574 border of the window. If \a height is negative, the function
1575 copies everything to the bottom of the window.
1577 The window system identifier (\c WId) can be retrieved using the
1578 QWidget::winId() function. The rationale for using a window
1579 identifier and not a QWidget, is to enable grabbing of windows
1580 that are not part of the application, window system frames, and so
1583 The grabWindow() function grabs pixels from the screen, not from
1584 the window, i.e. if there is another window partially or entirely
1585 over the one you grab, you get pixels from the overlying window,
1586 too. The mouse cursor is generally not grabbed.
1588 Note on X11 that if the given \a window doesn't have the same depth
1589 as the root window, and another window partially or entirely
1590 obscures the one you grab, you will \e not get pixels from the
1591 overlying window. The contents of the obscured areas in the
1592 pixmap will be undefined and uninitialized.
1594 On Windows Vista and above grabbing a layered window, which is
1595 created by setting the Qt::WA_TranslucentBackground attribute, will
1596 not work. Instead grabbing the desktop widget should work.
1598 \warning In general, grabbing an area outside the screen is not
1599 safe. This depends on the underlying window system.
1601 \warning The function is deprecated in Qt 5.0 since there might be
1602 platform plugins in which window system identifiers (\c WId)
1603 are local to a screen. Use QScreen::grabWindow() instead.
1605 \sa grabWidget(), {Screenshot Example}
1610 QPixmap QPixmap::grabWindow(WId window, int x, int y, int w, int h)
1612 qWarning("%s is deprecated, use QScreen::grabWindow() instead."
1613 " Defaulting to primary screen.", Q_FUNC_INFO);
1614 return QGuiApplication::primaryScreen()->grabWindow(window, x, y, w, h);
1620 QPlatformPixmap* QPixmap::handle() const
1625 #ifndef QT_NO_DEBUG_STREAM
1626 QDebug operator<<(QDebug dbg, const QPixmap &r)
1628 dbg.nospace() << "QPixmap(" << r.size() << ')';