source: trunk/src/gui/image/qpixmap.cpp@ 769

Last change on this file since 769 was 769, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.3 sources from branches/vendor/nokia/qt.

File size: 63.5 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the QtGui module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
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.
23**
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.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include <qglobal.h>
43
44#include "qpixmap.h"
45#include "qpixmapdata_p.h"
46#include "qimagepixmapcleanuphooks_p.h"
47
48#include "qbitmap.h"
49#include "qcolormap.h"
50#include "qimage.h"
51#include "qwidget.h"
52#include "qpainter.h"
53#include "qdatastream.h"
54#include "qbuffer.h"
55#include "qapplication.h"
56#include <private/qapplication_p.h>
57#include <private/qgraphicssystem_p.h>
58#include <private/qwidget_p.h>
59#include "qevent.h"
60#include "qfile.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"
67#include "qthread.h"
68
69#ifdef Q_WS_MAC
70# include "private/qt_mac_p.h"
71# include "private/qpixmap_mac_p.h"
72#endif
73
74#if defined(Q_WS_X11)
75# include "qx11info_x11.h"
76# include <private/qt_x11_p.h>
77# include <private/qpixmap_x11_p.h>
78#endif
79
80#if defined(Q_OS_SYMBIAN)
81# include <private/qt_s60_p.h>
82#endif
83
84#include "qpixmap_raster_p.h"
85
86QT_BEGIN_NAMESPACE
87
88// ### Qt 5: remove
89Q_GUI_EXPORT qint64 qt_pixmap_id(const QPixmap &pixmap)
90{
91 return pixmap.cacheKey();
92}
93
94static bool qt_pixmap_thread_test()
95{
96 if (!qApp) {
97 qFatal("QPixmap: Must construct a QApplication before a QPaintDevice");
98 return false;
99 }
100#ifndef Q_WS_WIN
101 if (qApp->thread() != QThread::currentThread()) {
102 qWarning("QPixmap: It is not safe to use pixmaps outside the GUI thread");
103 return false;
104 }
105#endif
106 return true;
107}
108
109void QPixmap::init(int w, int h, Type type)
110{
111 init(w, h, int(type));
112}
113
114void QPixmap::init(int w, int h, int type)
115{
116 if ((w > 0 && h > 0) || type == QPixmapData::BitmapType)
117 data = QPixmapData::create(w, h, (QPixmapData::PixelType) type);
118 else
119 data = 0;
120}
121
122/*!
123 \enum QPixmap::ColorMode
124
125 \compat
126
127 This enum type defines the color modes that exist for converting
128 QImage objects to QPixmap. It is provided here for compatibility
129 with earlier versions of Qt.
130
131 Use Qt::ImageConversionFlags instead.
132
133 \value Auto Select \c Color or \c Mono on a case-by-case basis.
134 \value Color Always create colored pixmaps.
135 \value Mono Always create bitmaps.
136*/
137
138/*!
139 Constructs a null pixmap.
140
141 \sa isNull()
142*/
143
144QPixmap::QPixmap()
145 : QPaintDevice()
146{
147 (void) qt_pixmap_thread_test();
148 init(0, 0, QPixmapData::PixmapType);
149}
150
151/*!
152 \fn QPixmap::QPixmap(int width, int height)
153
154 Constructs a pixmap with the given \a width and \a height. If
155 either \a width or \a height is zero, a null pixmap is
156 constructed.
157
158 \warning This will create a QPixmap with uninitialized data. Call
159 fill() to fill the pixmap with an appropriate color before drawing
160 onto it with QPainter.
161
162 \sa isNull()
163*/
164
165QPixmap::QPixmap(int w, int h)
166 : QPaintDevice()
167{
168 if (!qt_pixmap_thread_test())
169 init(0, 0, QPixmapData::PixmapType);
170 else
171 init(w, h, QPixmapData::PixmapType);
172}
173
174/*!
175 \overload
176
177 Constructs a pixmap of the given \a size.
178
179 \warning This will create a QPixmap with uninitialized data. Call
180 fill() to fill the pixmap with an appropriate color before drawing
181 onto it with QPainter.
182*/
183
184QPixmap::QPixmap(const QSize &size)
185 : QPaintDevice()
186{
187 if (!qt_pixmap_thread_test())
188 init(0, 0, QPixmapData::PixmapType);
189 else
190 init(size.width(), size.height(), QPixmapData::PixmapType);
191}
192
193/*!
194 \internal
195*/
196QPixmap::QPixmap(const QSize &s, Type type)
197{
198 if (!qt_pixmap_thread_test())
199 init(0, 0, type);
200 else
201 init(s.width(), s.height(), type);
202}
203
204/*!
205 \internal
206*/
207QPixmap::QPixmap(const QSize &s, int type)
208{
209 if (!qt_pixmap_thread_test())
210 init(0, 0, static_cast<QPixmapData::PixelType>(type));
211 else
212 init(s.width(), s.height(), static_cast<QPixmapData::PixelType>(type));
213}
214
215/*!
216 \internal
217*/
218QPixmap::QPixmap(QPixmapData *d)
219 : QPaintDevice(), data(d)
220{
221}
222
223/*!
224 Constructs a pixmap from the file with the given \a fileName. If the
225 file does not exist or is of an unknown format, the pixmap becomes a
226 null pixmap.
227
228 The loader attempts to read the pixmap using the specified \a
229 format. If the \a format is not specified (which is the default),
230 the loader probes the file for a header to guess the file format.
231
232 The file name can either refer to an actual file on disk or to
233 one of the application's embedded resources. See the
234 \l{resources.html}{Resource System} overview for details on how
235 to embed images and other resource files in the application's
236 executable.
237
238 If the image needs to be modified to fit in a lower-resolution
239 result (e.g. converting from 32-bit to 8-bit), use the \a
240 flags to control the conversion.
241
242 The \a fileName, \a format and \a flags parameters are
243 passed on to load(). This means that the data in \a fileName is
244 not compiled into the binary. If \a fileName contains a relative
245 path (e.g. the filename only) the relevant file must be found
246 relative to the runtime working directory.
247
248 \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
249 Image Files}
250*/
251
252QPixmap::QPixmap(const QString& fileName, const char *format, Qt::ImageConversionFlags flags)
253 : QPaintDevice()
254{
255 init(0, 0, QPixmapData::PixmapType);
256 if (!qt_pixmap_thread_test())
257 return;
258
259 load(fileName, format, flags);
260}
261
262/*!
263 Constructs a pixmap that is a copy of the given \a pixmap.
264
265 \sa copy()
266*/
267
268QPixmap::QPixmap(const QPixmap &pixmap)
269 : QPaintDevice()
270{
271 if (!qt_pixmap_thread_test()) {
272 init(0, 0, QPixmapData::PixmapType);
273 return;
274 }
275 if (pixmap.paintingActive()) { // make a deep copy
276 operator=(pixmap.copy());
277 } else {
278 data = pixmap.data;
279 }
280}
281
282/*!
283 Constructs a pixmap from the given \a xpm data, which must be a
284 valid XPM image.
285
286 Errors are silently ignored.
287
288 Note that it's possible to squeeze the XPM variable a little bit
289 by using an unusual declaration:
290
291 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 0
292
293 The extra \c const makes the entire definition read-only, which is
294 slightly more efficient (for example, when the code is in a shared
295 library) and ROMable when the application is to be stored in ROM.
296*/
297#ifndef QT_NO_IMAGEFORMAT_XPM
298QPixmap::QPixmap(const char * const xpm[])
299 : QPaintDevice()
300{
301 init(0, 0, QPixmapData::PixmapType);
302 if (!xpm)
303 return;
304
305 QImage image(xpm);
306 if (!image.isNull()) {
307 if (data && data->pixelType() == QPixmapData::BitmapType)
308 *this = QBitmap::fromImage(image);
309 else
310 *this = fromImage(image);
311 }
312}
313#endif
314
315
316/*!
317 Destroys the pixmap.
318*/
319
320QPixmap::~QPixmap()
321{
322 Q_ASSERT(!data || data->ref >= 1); // Catch if ref-counting changes again
323}
324
325/*!
326 \internal
327*/
328int QPixmap::devType() const
329{
330 return QInternal::Pixmap;
331}
332
333/*!
334 \fn QPixmap QPixmap::copy(int x, int y, int width, int height) const
335 \overload
336
337 Returns a deep copy of the subset of the pixmap that is specified
338 by the rectangle QRect( \a x, \a y, \a width, \a height).
339*/
340
341/*!
342 \fn QPixmap QPixmap::copy(const QRect &rectangle) const
343
344 Returns a deep copy of the subset of the pixmap that is specified
345 by the given \a rectangle. For more information on deep copies,
346 see the \l {Implicit Data Sharing} documentation.
347
348 If the given \a rectangle is empty, the whole image is copied.
349
350 \sa operator=(), QPixmap(), {QPixmap#Pixmap
351 Transformations}{Pixmap Transformations}
352*/
353QPixmap QPixmap::copy(const QRect &rect) const
354{
355 if (isNull())
356 return QPixmap();
357
358 QRect r(0, 0, width(), height());
359 if (!rect.isEmpty())
360 r = r.intersected(rect);
361
362 QPixmapData *d = data->createCompatiblePixmapData();
363 d->copy(data.data(), r);
364 return QPixmap(d);
365}
366
367/*!
368 \fn QPixmap::scroll(int dx, int dy, int x, int y, int width, int height, QRegion *exposed)
369 \since 4.6
370
371 This convenience function is equivalent to calling QPixmap::scroll(\a dx,
372 \a dy, QRect(\a x, \a y, \a width, \a height), \a exposed).
373
374 \sa QWidget::scroll(), QGraphicsItem::scroll()
375*/
376
377/*!
378 \since 4.6
379
380 Scrolls the area \a rect of this pixmap by (\a dx, \a dy). The exposed
381 region is left unchanged. You can optionally pass a pointer to an empty
382 QRegion to get the region that is \a exposed by the scroll operation.
383
384 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 2
385
386 You cannot scroll while there is an active painter on the pixmap.
387
388 \sa QWidget::scroll(), QGraphicsItem::scroll()
389*/
390void QPixmap::scroll(int dx, int dy, const QRect &rect, QRegion *exposed)
391{
392 if (isNull() || (dx == 0 && dy == 0))
393 return;
394 QRect dest = rect & this->rect();
395 QRect src = dest.translated(-dx, -dy) & dest;
396 if (src.isEmpty()) {
397 if (exposed)
398 *exposed += dest;
399 return;
400 }
401
402 detach();
403
404 if (!data->scroll(dx, dy, src)) {
405 // Fallback
406 QPixmap pix = *this;
407 QPainter painter(&pix);
408 painter.setCompositionMode(QPainter::CompositionMode_Source);
409 painter.drawPixmap(src.translated(dx, dy), *this, src);
410 painter.end();
411 *this = pix;
412 }
413
414 if (exposed) {
415 *exposed += dest;
416 *exposed -= src.translated(dx, dy);
417 }
418}
419
420/*!
421 Assigns the given \a pixmap to this pixmap and returns a reference
422 to this pixmap.
423
424 \sa copy(), QPixmap()
425*/
426
427QPixmap &QPixmap::operator=(const QPixmap &pixmap)
428{
429 if (paintingActive()) {
430 qWarning("QPixmap::operator=: Cannot assign to pixmap during painting");
431 return *this;
432 }
433 if (pixmap.paintingActive()) { // make a deep copy
434 *this = pixmap.copy();
435 } else {
436 data = pixmap.data;
437 }
438 return *this;
439}
440
441/*!
442 Returns the pixmap as a QVariant.
443*/
444QPixmap::operator QVariant() const
445{
446 return QVariant(QVariant::Pixmap, this);
447}
448
449/*!
450 \fn bool QPixmap::operator!() const
451
452 Returns true if this is a null pixmap; otherwise returns false.
453
454 \sa isNull()
455*/
456
457/*!
458 \fn QPixmap::operator QImage() const
459
460 Returns the pixmap as a QImage.
461
462 Use the toImage() function instead.
463*/
464
465/*!
466 Converts the pixmap to a QImage. Returns a null image if the
467 conversion fails.
468
469 If the pixmap has 1-bit depth, the returned image will also be 1
470 bit deep. Images with more bits will be returned in a format
471 closely represents the underlying system. Usually this will be
472 QImage::Format_ARGB32_Premultiplied for pixmaps with an alpha and
473 QImage::Format_RGB32 or QImage::Format_RGB16 for pixmaps without
474 alpha.
475
476 Note that for the moment, alpha masks on monochrome images are
477 ignored.
478
479 \sa fromImage(), {QImage#Image Formats}{Image Formats}
480*/
481QImage QPixmap::toImage() const
482{
483 if (isNull())
484 return QImage();
485
486 return data->toImage();
487}
488
489/*!
490 \fn QMatrix QPixmap::trueMatrix(const QTransform &matrix, int width, int height)
491
492 Returns the actual matrix used for transforming a pixmap with the
493 given \a width, \a height and \a matrix.
494
495 When transforming a pixmap using the transformed() function, the
496 transformation matrix is internally adjusted to compensate for
497 unwanted translation, i.e. transformed() returns the smallest
498 pixmap containing all transformed points of the original
499 pixmap. This function returns the modified matrix, which maps
500 points correctly from the original pixmap into the new pixmap.
501
502 \sa transformed(), {QPixmap#Pixmap Transformations}{Pixmap
503 Transformations}
504*/
505QTransform QPixmap::trueMatrix(const QTransform &m, int w, int h)
506{
507 return QImage::trueMatrix(m, w, h);
508}
509
510/*!
511 \overload
512
513 This convenience function loads the matrix \a m into a
514 QTransform and calls the overloaded function with the
515 QTransform and the width \a w and the height \a h.
516 */
517QMatrix QPixmap::trueMatrix(const QMatrix &m, int w, int h)
518{
519 return trueMatrix(QTransform(m), w, h).toAffine();
520}
521
522
523/*!
524 \fn bool QPixmap::isQBitmap() const
525
526 Returns true if this is a QBitmap; otherwise returns false.
527*/
528
529bool QPixmap::isQBitmap() const
530{
531 return data->type == QPixmapData::BitmapType;
532}
533
534/*!
535 \fn bool QPixmap::isNull() const
536
537 Returns true if this is a null pixmap; otherwise returns false.
538
539 A null pixmap has zero width, zero height and no contents. You
540 cannot draw in a null pixmap.
541*/
542bool QPixmap::isNull() const
543{
544 return !data || data->isNull();
545}
546
547/*!
548 \fn int QPixmap::width() const
549
550 Returns the width of the pixmap.
551
552 \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
553*/
554int QPixmap::width() const
555{
556 return data ? data->width() : 0;
557}
558
559/*!
560 \fn int QPixmap::height() const
561
562 Returns the height of the pixmap.
563
564 \sa size(), {QPixmap#Pixmap Information}{Pixmap Information}
565*/
566int QPixmap::height() const
567{
568 return data ? data->height() : 0;
569}
570
571/*!
572 \fn QSize QPixmap::size() const
573
574 Returns the size of the pixmap.
575
576 \sa width(), height(), {QPixmap#Pixmap Information}{Pixmap
577 Information}
578*/
579QSize QPixmap::size() const
580{
581 return data ? QSize(data->width(), data->height()) : QSize();
582}
583
584/*!
585 \fn QRect QPixmap::rect() const
586
587 Returns the pixmap's enclosing rectangle.
588
589 \sa {QPixmap#Pixmap Information}{Pixmap Information}
590*/
591QRect QPixmap::rect() const
592{
593 return data ? QRect(0, 0, data->width(), data->height()) : QRect();
594}
595
596/*!
597 \fn int QPixmap::depth() const
598
599 Returns the depth of the pixmap.
600
601 The pixmap depth is also called bits per pixel (bpp) or bit planes
602 of a pixmap. A null pixmap has depth 0.
603
604 \sa defaultDepth(), {QPixmap#Pixmap Information}{Pixmap
605 Information}
606*/
607int QPixmap::depth() const
608{
609 return data ? data->depth() : 0;
610}
611
612/*!
613 \fn void QPixmap::resize(const QSize &size)
614 \overload
615 \compat
616
617 Use QPixmap::copy() instead to get the pixmap with the new size.
618
619 \oldcode
620 pixmap.resize(size);
621 \newcode
622 pixmap = pixmap.copy(QRect(QPoint(0, 0), size));
623 \endcode
624*/
625#ifdef QT3_SUPPORT
626void QPixmap::resize_helper(const QSize &s)
627{
628 int w = s.width();
629 int h = s.height();
630 if (w < 1 || h < 1) {
631 *this = QPixmap();
632 return;
633 }
634
635 if (size() == s)
636 return;
637
638 // Create new pixmap
639 QPixmap pm(QSize(w, h), data ? data->type : QPixmapData::PixmapType);
640 bool uninit = false;
641#if defined(Q_WS_X11)
642 QX11PixmapData *x11Data = data && data->classId() == QPixmapData::X11Class ? static_cast<QX11PixmapData*>(data.data()) : 0;
643 if (x11Data) {
644 pm.x11SetScreen(x11Data->xinfo.screen());
645 uninit = x11Data->flags & QX11PixmapData::Uninitialized;
646 }
647#elif defined(Q_WS_MAC)
648 QMacPixmapData *macData = data && data->classId() == QPixmapData::MacClass ? static_cast<QMacPixmapData*>(data.data()) : 0;
649 if (macData)
650 uninit = macData->uninit;
651#endif
652 if (!uninit && !isNull()) {
653 // Copy old pixmap
654 if (hasAlphaChannel())
655 pm.fill(Qt::transparent);
656 QPainter p(&pm);
657 p.drawPixmap(0, 0, *this, 0, 0, qMin(width(), w), qMin(height(), h));
658 }
659
660#if defined(Q_WS_X11)
661 if (x11Data && x11Data->x11_mask) {
662 QX11PixmapData *pmData = static_cast<QX11PixmapData*>(pm.data.data());
663 pmData->x11_mask = (Qt::HANDLE)XCreatePixmap(X11->display,
664 RootWindow(x11Data->xinfo.display(),
665 x11Data->xinfo.screen()),
666 w, h, 1);
667 GC gc = XCreateGC(X11->display, pmData->x11_mask, 0, 0);
668 XCopyArea(X11->display, x11Data->x11_mask, pmData->x11_mask, gc, 0, 0, qMin(width(), w), qMin(height(), h), 0, 0);
669 XFreeGC(X11->display, gc);
670 }
671#endif
672 *this = pm;
673}
674#endif
675
676/*!
677 \fn void QPixmap::resize(int width, int height)
678 \compat
679
680 Use QPixmap::copy() instead to get the pixmap with the new size.
681
682 \oldcode
683 pixmap.resize(10, 20);
684 \newcode
685 pixmap = pixmap.copy(0, 0, 10, 20);
686 \endcode
687*/
688
689/*!
690 \fn bool QPixmap::selfMask() const
691 \compat
692
693 Returns whether the pixmap is its own mask or not.
694
695 This function is no longer relevant since the concept of self
696 masking doesn't exists anymore.
697*/
698
699/*!
700 Sets a mask bitmap.
701
702 This function merges the \a mask with the pixmap's alpha channel. A pixel
703 value of 1 on the mask means the pixmap's pixel is unchanged; a value of 0
704 means the pixel is transparent. The mask must have the same size as this
705 pixmap.
706
707 Setting a null mask resets the mask, leaving the previously transparent
708 pixels black. The effect of this function is undefined when the pixmap is
709 being painted on.
710
711 \warning This is potentially an expensive operation.
712
713 \sa mask(), {QPixmap#Pixmap Transformations}{Pixmap Transformations},
714 QBitmap
715*/
716void QPixmap::setMask(const QBitmap &mask)
717{
718 if (paintingActive()) {
719 qWarning("QPixmap::setMask: Cannot set mask while pixmap is being painted on");
720 return;
721 }
722
723 if (!mask.isNull() && mask.size() != size()) {
724 qWarning("QPixmap::setMask() mask size differs from pixmap size");
725 return;
726 }
727
728 if (isNull())
729 return;
730
731 if (static_cast<const QPixmap &>(mask).data == data) // trying to selfmask
732 return;
733
734 detach();
735 data->setMask(mask);
736}
737
738#ifndef QT_NO_IMAGE_HEURISTIC_MASK
739/*!
740 Creates and returns a heuristic mask for this pixmap.
741
742 The function works by selecting a color from one of the corners
743 and then chipping away pixels of that color, starting at all the
744 edges. If \a clipTight is true (the default) the mask is just
745 large enough to cover the pixels; otherwise, the mask is larger
746 than the data pixels.
747
748 The mask may not be perfect but it should be reasonable, so you
749 can do things such as the following:
750
751 \snippet doc/src/snippets/code/src_gui_image_qpixmap.cpp 1
752
753 This function is slow because it involves converting to/from a
754 QImage, and non-trivial computations.
755
756 \sa QImage::createHeuristicMask(), createMaskFromColor()
757*/
758QBitmap QPixmap::createHeuristicMask(bool clipTight) const
759{
760 QBitmap m = QBitmap::fromImage(toImage().createHeuristicMask(clipTight));
761 return m;
762}
763#endif
764
765/*!
766 Creates and returns a mask for this pixmap based on the given \a
767 maskColor. If the \a mode is Qt::MaskInColor, all pixels matching the
768 maskColor will be opaque. If \a mode is Qt::MaskOutColor, all pixels
769 matching the maskColor will be transparent.
770
771 This function is slow because it involves converting to/from a
772 QImage.
773
774 \sa createHeuristicMask(), QImage::createMaskFromColor()
775*/
776QBitmap QPixmap::createMaskFromColor(const QColor &maskColor, Qt::MaskMode mode) const
777{
778 QImage image = toImage().convertToFormat(QImage::Format_ARGB32);
779 return QBitmap::fromImage(image.createMaskFromColor(maskColor.rgba(), mode));
780}
781
782/*! \overload
783
784 Creates and returns a mask for this pixmap based on the given \a
785 maskColor. Same as calling createMaskFromColor(maskColor,
786 Qt::MaskInColor)
787
788 \sa createHeuristicMask(), QImage::createMaskFromColor()
789*/
790QBitmap QPixmap::createMaskFromColor(const QColor &maskColor) const
791{
792 return createMaskFromColor(maskColor, Qt::MaskInColor);
793}
794
795/*!
796 Loads a pixmap from the file with the given \a fileName. Returns
797 true if the pixmap was successfully loaded; otherwise returns
798 false.
799
800 The loader attempts to read the pixmap using the specified \a
801 format. If the \a format is not specified (which is the default),
802 the loader probes the file for a header to guess the file format.
803
804 The file name can either refer to an actual file on disk or to one
805 of the application's embedded resources. See the
806 \l{resources.html}{Resource System} overview for details on how to
807 embed pixmaps and other resource files in the application's
808 executable.
809
810 If the data needs to be modified to fit in a lower-resolution
811 result (e.g. converting from 32-bit to 8-bit), use the \a flags to
812 control the conversion.
813
814 Note that QPixmaps are automatically added to the QPixmapCache
815 when loaded from a file; the key used is internal and can not
816 be acquired.
817
818 \sa loadFromData(), {QPixmap#Reading and Writing Image
819 Files}{Reading and Writing Image Files}
820*/
821
822bool QPixmap::load(const QString &fileName, const char *format, Qt::ImageConversionFlags flags)
823{
824 if (fileName.isEmpty())
825 return false;
826
827 QFileInfo info(fileName);
828 QString key = QLatin1String("qt_pixmap_") + info.absoluteFilePath() + QLatin1Char('_') + QString::number(info.lastModified().toTime_t()) + QLatin1Char('_') +
829 QString::number(info.size()) + QLatin1Char('_') + QString::number(data ? data->pixelType() : QPixmapData::PixmapType);
830
831 if (QPixmapCache::find(key, *this))
832 return true;
833
834 QScopedPointer<QPixmapData> tmp(QPixmapData::create(0, 0, data ? data->type : QPixmapData::PixmapType));
835 if (tmp->fromFile(fileName, format, flags)) {
836 data = tmp.take();
837 QPixmapCache::insert(key, *this);
838 return true;
839 }
840
841 return false;
842}
843
844/*!
845 \fn bool QPixmap::loadFromData(const uchar *data, uint len, const char *format, Qt::ImageConversionFlags flags)
846
847 Loads a pixmap from the \a len first bytes of the given binary \a
848 data. Returns true if the pixmap was loaded successfully;
849 otherwise returns false.
850
851 The loader attempts to read the pixmap using the specified \a
852 format. If the \a format is not specified (which is the default),
853 the loader probes the file for a header to guess the file format.
854
855 If the data needs to be modified to fit in a lower-resolution
856 result (e.g. converting from 32-bit to 8-bit), use the \a flags to
857 control the conversion.
858
859 \sa load(), {QPixmap#Reading and Writing Image Files}{Reading and
860 Writing Image Files}
861*/
862
863bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, Qt::ImageConversionFlags flags)
864{
865 if (len == 0 || buf == 0)
866 return false;
867
868 if (!data)
869 data = QPixmapData::create(0, 0, QPixmapData::PixmapType);
870
871 return data->fromData(buf, len, format, flags);
872}
873
874/*!
875 \fn bool QPixmap::loadFromData(const QByteArray &data, const char *format, Qt::ImageConversionFlags flags)
876
877 \overload
878
879 Loads a pixmap from the binary \a data using the specified \a
880 format and conversion \a flags.
881*/
882
883
884/*!
885 Saves the pixmap to the file with the given \a fileName using the
886 specified image file \a format and \a quality factor. Returns true
887 if successful; otherwise returns false.
888
889 The \a quality factor must be in the range [0,100] or -1. Specify
890 0 to obtain small compressed files, 100 for large uncompressed
891 files, and -1 to use the default settings.
892
893 If \a format is 0, an image format will be chosen from \a fileName's
894 suffix.
895
896 \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
897 Image Files}
898*/
899
900bool QPixmap::save(const QString &fileName, const char *format, int quality) const
901{
902 if (isNull())
903 return false; // nothing to save
904 QImageWriter writer(fileName, format);
905 return doImageIO(&writer, quality);
906}
907
908/*!
909 \overload
910
911 This function writes a QPixmap to the given \a device using the
912 specified image file \a format and \a quality factor. This can be
913 used, for example, to save a pixmap directly into a QByteArray:
914
915 \snippet doc/src/snippets/image/image.cpp 1
916*/
917
918bool QPixmap::save(QIODevice* device, const char* format, int quality) const
919{
920 if (isNull())
921 return false; // nothing to save
922 QImageWriter writer(device, format);
923 return doImageIO(&writer, quality);
924}
925
926/*! \internal
927*/
928bool QPixmap::doImageIO(QImageWriter *writer, int quality) const
929{
930 if (quality > 100 || quality < -1)
931 qWarning("QPixmap::save: quality out of range [-1,100]");
932 if (quality >= 0)
933 writer->setQuality(qMin(quality,100));
934 return writer->write(toImage());
935}
936
937
938// The implementation (and documentation) of
939// QPixmap::fill(const QWidget *, const QPoint &)
940// is in qwidget.cpp
941
942/*!
943 \fn void QPixmap::fill(const QWidget *widget, int x, int y)
944 \overload
945
946 Fills the pixmap with the \a widget's background color or pixmap.
947 The given point, (\a x, \a y), defines an offset in widget
948 coordinates to which the pixmap's top-left pixel will be mapped
949 to.
950*/
951
952/*!
953 Fills the pixmap with the given \a color.
954
955 The effect of this function is undefined when the pixmap is
956 being painted on.
957
958 \sa {QPixmap#Pixmap Transformations}{Pixmap Transformations}
959*/
960
961void QPixmap::fill(const QColor &color)
962{
963 if (isNull())
964 return;
965
966 // Some people are probably already calling fill while a painter is active, so to not break
967 // their programs, only print a warning and return when the fill operation could cause a crash.
968 if (paintingActive() && (color.alpha() != 255) && !hasAlphaChannel()) {
969 qWarning("QPixmap::fill: Cannot fill while pixmap is being painted on");
970 return;
971 }
972
973 if (data->ref == 1) {
974 // detach() will also remove this pixmap from caches, so
975 // it has to be called even when ref == 1.
976 detach();
977 } else {
978 // Don't bother to make a copy of the data object, since
979 // it will be filled with new pixel data anyway.
980 QPixmapData *d = data->createCompatiblePixmapData();
981 d->resize(data->width(), data->height());
982 data = d;
983 }
984 data->fill(color);
985}
986
987/*! \obsolete
988 Returns a number that identifies the contents of this QPixmap
989 object. Distinct QPixmap objects can only have the same serial
990 number if they refer to the same contents (but they don't have
991 to).
992
993 Use cacheKey() instead.
994
995 \warning The serial number doesn't necessarily change when
996 the pixmap is altered. This means that it may be dangerous to use
997 it as a cache key. For caching pixmaps, we recommend using the
998 QPixmapCache class whenever possible.
999*/
1000int QPixmap::serialNumber() const
1001{
1002 if (isNull())
1003 return 0;
1004 return data->serialNumber();
1005}
1006
1007/*!
1008 Returns a number that identifies this QPixmap. Distinct QPixmap
1009 objects can only have the same cache key if they refer to the same
1010 contents.
1011
1012 The cacheKey() will change when the pixmap is altered.
1013*/
1014qint64 QPixmap::cacheKey() const
1015{
1016 if (isNull())
1017 return 0;
1018
1019 Q_ASSERT(data);
1020 return data->cacheKey();
1021}
1022
1023static void sendResizeEvents(QWidget *target)
1024{
1025 QResizeEvent e(target->size(), QSize());
1026 QApplication::sendEvent(target, &e);
1027
1028 const QObjectList children = target->children();
1029 for (int i = 0; i < children.size(); ++i) {
1030 QWidget *child = static_cast<QWidget*>(children.at(i));
1031 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
1032 sendResizeEvents(child);
1033 }
1034}
1035
1036/*!
1037 \fn QPixmap QPixmap::grabWidget(QWidget * widget, const QRect &rectangle)
1038
1039 Creates a pixmap and paints the given \a widget, restricted by the
1040 given \a rectangle, in it. If the \a widget has any children, then
1041 they are also painted in the appropriate positions.
1042
1043 If no rectangle is specified (the default) the entire widget is
1044 painted.
1045
1046 If \a widget is 0, the specified rectangle doesn't overlap the
1047 widget's rectangle, or an error occurs, the function will return a
1048 null QPixmap. If the rectangle is a superset of the given \a
1049 widget, the areas outside the \a widget are covered with the
1050 widget's background.
1051
1052 This function actually asks \a widget to paint itself (and its
1053 children to paint themselves) by calling paintEvent() with painter
1054 redirection turned on. But QPixmap also provides the grabWindow()
1055 function which is a bit faster by grabbing pixels directly off the
1056 screen. In addition, if there are overlaying windows,
1057 grabWindow(), unlike grabWidget(), will see them.
1058
1059 \warning Do not grab a widget from its QWidget::paintEvent().
1060 However, it is safe to grab a widget from another widget's
1061 \l {QWidget::}{paintEvent()}.
1062
1063 \sa grabWindow()
1064*/
1065
1066QPixmap QPixmap::grabWidget(QWidget * widget, const QRect &rect)
1067{
1068 if (!widget)
1069 return QPixmap();
1070
1071 if (widget->testAttribute(Qt::WA_PendingResizeEvent) || !widget->testAttribute(Qt::WA_WState_Created))
1072 sendResizeEvents(widget);
1073
1074 QRect r(rect);
1075 if (r.width() < 0)
1076 r.setWidth(widget->width() - rect.x());
1077 if (r.height() < 0)
1078 r.setHeight(widget->height() - rect.y());
1079
1080 if (!r.intersects(widget->rect()))
1081 return QPixmap();
1082
1083 QPixmap res(r.size());
1084 widget->render(&res, QPoint(), r,
1085 QWidget::DrawWindowBackground | QWidget::DrawChildren | QWidget::IgnoreMask);
1086 return res;
1087}
1088
1089/*!
1090 \fn QPixmap QPixmap::grabWidget(QWidget *widget, int x, int y, int
1091 width, int height)
1092
1093 \overload
1094
1095 Creates a pixmap and paints the given \a widget, restricted by
1096 QRect(\a x, \a y, \a width, \a height), in it.
1097
1098 \warning Do not grab a widget from its QWidget::paintEvent().
1099 However, it is safe to grab a widget from another widget's
1100 \l {QWidget::}{paintEvent()}.
1101*/
1102
1103
1104/*!
1105 \since 4.5
1106
1107 \enum QPixmap::ShareMode
1108
1109 This enum type defines the share modes that are available when
1110 creating a QPixmap object from a raw X11 Pixmap handle.
1111
1112 \value ImplicitlyShared This mode will cause the QPixmap object to
1113 create a copy of the internal data before it is modified, thus
1114 keeping the original X11 pixmap intact.
1115
1116 \value ExplicitlyShared In this mode, the pixmap data will \e not be
1117 copied before it is modified, which in effect will change the
1118 original X11 pixmap.
1119
1120 \warning This enum is only used for X11 specific functions; using
1121 it is non-portable.
1122
1123 \sa QPixmap::fromX11Pixmap()
1124*/
1125
1126/*!
1127 \since 4.5
1128
1129 \fn QPixmap QPixmap::fromX11Pixmap(Qt::HANDLE pixmap, QPixmap::ShareMode mode)
1130
1131 Creates a QPixmap from the native X11 Pixmap handle \a pixmap,
1132 using \a mode as the share mode. The default share mode is
1133 QPixmap::ImplicitlyShared, which means that a copy of the pixmap is
1134 made if someone tries to modify it by e.g. drawing onto it.
1135
1136 QPixmap does \e not take ownership of the \a pixmap handle, and
1137 have to be deleted by the user.
1138
1139 \warning This function is X11 specific; using it is non-portable.
1140
1141 \sa QPixmap::ShareMode
1142*/
1143
1144
1145#if defined(Q_WS_X11) || defined(Q_WS_QWS)
1146
1147/*!
1148 Returns the pixmap's handle to the device context.
1149
1150 Note that, since QPixmap make use of \l {Implicit Data
1151 Sharing}{implicit data sharing}, the detach() function must be
1152 called explicitly to ensure that only \e this pixmap's data is
1153 modified if the pixmap data is shared.
1154
1155 \warning This function is X11 specific; using it is non-portable.
1156
1157 \sa detach()
1158*/
1159
1160Qt::HANDLE QPixmap::handle() const
1161{
1162#if defined(Q_WS_X11)
1163 if (data && data->classId() == QPixmapData::X11Class)
1164 return static_cast<const QX11PixmapData*>(data.constData())->handle();
1165#endif
1166 return 0;
1167}
1168#endif
1169
1170
1171#ifdef QT3_SUPPORT
1172static Qt::ImageConversionFlags colorModeToFlags(QPixmap::ColorMode mode)
1173{
1174 Qt::ImageConversionFlags flags = Qt::AutoColor;
1175 switch (mode) {
1176 case QPixmap::Color:
1177 flags |= Qt::ColorOnly;
1178 break;
1179 case QPixmap::Mono:
1180 flags |= Qt::MonoOnly;
1181 break;
1182 default:
1183 break;// Nothing.
1184 }
1185 return flags;
1186}
1187
1188/*!
1189 Use the constructor that takes a Qt::ImageConversionFlag instead.
1190*/
1191
1192QPixmap::QPixmap(const QString& fileName, const char *format, ColorMode mode)
1193 : QPaintDevice()
1194{
1195 init(0, 0, QPixmapData::PixmapType);
1196 if (!qt_pixmap_thread_test())
1197 return;
1198
1199 load(fileName, format, colorModeToFlags(mode));
1200}
1201
1202/*!
1203 Constructs a pixmap from the QImage \a image.
1204
1205 Use the static fromImage() function instead.
1206*/
1207QPixmap::QPixmap(const QImage& image)
1208 : QPaintDevice()
1209{
1210 init(0, 0, QPixmapData::PixmapType);
1211 if (!qt_pixmap_thread_test())
1212 return;
1213
1214 if (data && data->pixelType() == QPixmapData::BitmapType)
1215 *this = QBitmap::fromImage(image);
1216 else
1217 *this = fromImage(image);
1218}
1219
1220/*!
1221 \overload
1222
1223 Converts the given \a image to a pixmap that is assigned to this
1224 pixmap.
1225
1226 Use the static fromImage() function instead.
1227*/
1228
1229QPixmap &QPixmap::operator=(const QImage &image)
1230{
1231 if (data && data->pixelType() == QPixmapData::BitmapType)
1232 *this = QBitmap::fromImage(image);
1233 else
1234 *this = fromImage(image);
1235 return *this;
1236}
1237
1238/*!
1239 Use the load() function that takes a Qt::ImageConversionFlag instead.
1240*/
1241
1242bool QPixmap::load(const QString &fileName, const char *format, ColorMode mode)
1243{
1244 return load(fileName, format, colorModeToFlags(mode));
1245}
1246
1247/*!
1248 Use the loadFromData() function that takes a Qt::ImageConversionFlag instead.
1249*/
1250
1251bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, ColorMode mode)
1252{
1253 return loadFromData(buf, len, format, colorModeToFlags(mode));
1254}
1255
1256/*!
1257 Use the static fromImage() function instead.
1258*/
1259bool QPixmap::convertFromImage(const QImage &image, ColorMode mode)
1260{
1261 if (data && data->pixelType() == QPixmapData::BitmapType)
1262 *this = QBitmap::fromImage(image, colorModeToFlags(mode));
1263 else
1264 *this = fromImage(image, colorModeToFlags(mode));
1265 return !isNull();
1266}
1267
1268#endif
1269
1270/*****************************************************************************
1271 QPixmap stream functions
1272 *****************************************************************************/
1273#if !defined(QT_NO_DATASTREAM)
1274/*!
1275 \relates QPixmap
1276
1277 Writes the given \a pixmap to the given \a stream as a PNG
1278 image. Note that writing the stream to a file will not produce a
1279 valid image file.
1280
1281 \sa QPixmap::save(), {Format of the QDataStream Operators}
1282*/
1283
1284QDataStream &operator<<(QDataStream &stream, const QPixmap &pixmap)
1285{
1286 return stream << pixmap.toImage();
1287}
1288
1289/*!
1290 \relates QPixmap
1291
1292 Reads an image from the given \a stream into the given \a pixmap.
1293
1294 \sa QPixmap::load(), {Format of the QDataStream Operators}
1295*/
1296
1297QDataStream &operator>>(QDataStream &stream, QPixmap &pixmap)
1298{
1299 QImage image;
1300 stream >> image;
1301
1302 if (image.isNull()) {
1303 pixmap = QPixmap();
1304 } else if (image.depth() == 1) {
1305 pixmap = QBitmap::fromImage(image);
1306 } else {
1307 pixmap = QPixmap::fromImage(image);
1308 }
1309 return stream;
1310}
1311
1312#endif // QT_NO_DATASTREAM
1313
1314#ifdef QT3_SUPPORT
1315Q_GUI_EXPORT void copyBlt(QPixmap *dst, int dx, int dy,
1316 const QPixmap *src, int sx, int sy, int sw, int sh)
1317{
1318 Q_ASSERT_X(dst, "::copyBlt", "Destination pixmap must be non-null");
1319 Q_ASSERT_X(src, "::copyBlt", "Source pixmap must be non-null");
1320
1321 if (src->hasAlphaChannel()) {
1322 if (dst->paintEngine()->hasFeature(QPaintEngine::PorterDuff)) {
1323 QPainter p(dst);
1324 p.setCompositionMode(QPainter::CompositionMode_Source);
1325 p.drawPixmap(dx, dy, *src, sx, sy, sw, sh);
1326 } else {
1327 QImage image = dst->toImage().convertToFormat(QImage::Format_ARGB32_Premultiplied);
1328 QPainter p(&image);
1329 p.setCompositionMode(QPainter::CompositionMode_Source);
1330 p.drawPixmap(dx, dy, *src, sx, sy, sw, sh);
1331 p.end();
1332 *dst = QPixmap::fromImage(image);
1333 }
1334 } else {
1335 QPainter p(dst);
1336 p.drawPixmap(dx, dy, *src, sx, sy, sw, sh);
1337 }
1338
1339}
1340#endif
1341
1342/*!
1343 \internal
1344*/
1345
1346bool QPixmap::isDetached() const
1347{
1348 return data && data->ref == 1;
1349}
1350
1351/*! \internal
1352 ### Qt5 - remove me.
1353*/
1354void QPixmap::deref()
1355{
1356 Q_ASSERT_X(false, "QPixmap::deref()", "Do not call this function anymore!");
1357}
1358
1359/*!
1360 \fn QImage QPixmap::convertToImage() const
1361
1362 Use the toImage() function instead.
1363*/
1364
1365/*!
1366 \fn bool QPixmap::convertFromImage(const QImage &image, Qt::ImageConversionFlags flags)
1367
1368 Use the static fromImage() function instead.
1369*/
1370
1371/*!
1372 \fn QPixmap QPixmap::xForm(const QMatrix &matrix) const
1373
1374 Use transformed() instead.
1375*/
1376
1377/*!
1378 \fn QPixmap QPixmap::scaled(int width, int height,
1379 Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode
1380 transformMode) const
1381
1382 \overload
1383
1384 Returns a copy of the pixmap scaled to a rectangle with the given
1385 \a width and \a height according to the given \a aspectRatioMode and
1386 \a transformMode.
1387
1388 If either the \a width or the \a height is zero or negative, this
1389 function returns a null pixmap.
1390*/
1391
1392/*!
1393 \fn QPixmap QPixmap::scaled(const QSize &size, Qt::AspectRatioMode
1394 aspectRatioMode, Qt::TransformationMode transformMode) const
1395
1396 Scales the pixmap to the given \a size, using the aspect ratio and
1397 transformation modes specified by \a aspectRatioMode and \a
1398 transformMode.
1399
1400 \image qimage-scaling.png
1401
1402 \list
1403 \i If \a aspectRatioMode is Qt::IgnoreAspectRatio, the pixmap
1404 is scaled to \a size.
1405 \i If \a aspectRatioMode is Qt::KeepAspectRatio, the pixmap is
1406 scaled to a rectangle as large as possible inside \a size, preserving the aspect ratio.
1407 \i If \a aspectRatioMode is Qt::KeepAspectRatioByExpanding,
1408 the pixmap is scaled to a rectangle as small as possible
1409 outside \a size, preserving the aspect ratio.
1410 \endlist
1411
1412 If the given \a size is empty, this function returns a null
1413 pixmap.
1414
1415
1416 In some cases it can be more beneficial to draw the pixmap to a
1417 painter with a scale set rather than scaling the pixmap. This is
1418 the case when the painter is for instance based on OpenGL or when
1419 the scale factor changes rapidly.
1420
1421 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1422 Transformations}
1423
1424*/
1425QPixmap QPixmap::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::TransformationMode mode) const
1426{
1427 if (isNull()) {
1428 qWarning("QPixmap::scaled: Pixmap is a null pixmap");
1429 return QPixmap();
1430 }
1431 if (s.isEmpty())
1432 return QPixmap();
1433
1434 QSize newSize = size();
1435 newSize.scale(s, aspectMode);
1436 if (newSize == size())
1437 return *this;
1438
1439 QTransform wm = QTransform::fromScale((qreal)newSize.width() / width(),
1440 (qreal)newSize.height() / height());
1441 QPixmap pix = transformed(wm, mode);
1442 return pix;
1443}
1444
1445/*!
1446 \fn QPixmap QPixmap::scaledToWidth(int width, Qt::TransformationMode
1447 mode) const
1448
1449 Returns a scaled copy of the image. The returned image is scaled
1450 to the given \a width using the specified transformation \a mode.
1451 The height of the pixmap is automatically calculated so that the
1452 aspect ratio of the pixmap is preserved.
1453
1454 If \a width is 0 or negative, a null pixmap is returned.
1455
1456 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1457 Transformations}
1458*/
1459QPixmap QPixmap::scaledToWidth(int w, Qt::TransformationMode mode) const
1460{
1461 if (isNull()) {
1462 qWarning("QPixmap::scaleWidth: Pixmap is a null pixmap");
1463 return copy();
1464 }
1465 if (w <= 0)
1466 return QPixmap();
1467
1468 qreal factor = (qreal) w / width();
1469 QTransform wm = QTransform::fromScale(factor, factor);
1470 return transformed(wm, mode);
1471}
1472
1473/*!
1474 \fn QPixmap QPixmap::scaledToHeight(int height,
1475 Qt::TransformationMode mode) const
1476
1477 Returns a scaled copy of the image. The returned image is scaled
1478 to the given \a height using the specified transformation \a mode.
1479 The width of the pixmap is automatically calculated so that the
1480 aspect ratio of the pixmap is preserved.
1481
1482 If \a height is 0 or negative, a null pixmap is returned.
1483
1484 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1485 Transformations}
1486*/
1487QPixmap QPixmap::scaledToHeight(int h, Qt::TransformationMode mode) const
1488{
1489 if (isNull()) {
1490 qWarning("QPixmap::scaleHeight: Pixmap is a null pixmap");
1491 return copy();
1492 }
1493 if (h <= 0)
1494 return QPixmap();
1495
1496 qreal factor = (qreal) h / height();
1497 QTransform wm = QTransform::fromScale(factor, factor);
1498 return transformed(wm, mode);
1499}
1500
1501/*!
1502 Returns a copy of the pixmap that is transformed using the given
1503 transformation \a transform and transformation \a mode. The original
1504 pixmap is not changed.
1505
1506 The transformation \a transform is internally adjusted to compensate
1507 for unwanted translation; i.e. the pixmap produced is the smallest
1508 pixmap that contains all the transformed points of the original
1509 pixmap. Use the trueMatrix() function to retrieve the actual
1510 matrix used for transforming the pixmap.
1511
1512 This function is slow because it involves transformation to a
1513 QImage, non-trivial computations and a transformation back to a
1514 QPixmap.
1515
1516 \sa trueMatrix(), {QPixmap#Pixmap Transformations}{Pixmap
1517 Transformations}
1518*/
1519QPixmap QPixmap::transformed(const QTransform &transform,
1520 Qt::TransformationMode mode) const
1521{
1522 if (isNull() || transform.type() <= QTransform::TxTranslate)
1523 return *this;
1524
1525 return data->transformed(transform, mode);
1526}
1527
1528/*!
1529 \overload
1530
1531 This convenience function loads the \a matrix into a
1532 QTransform and calls the overloaded function.
1533 */
1534QPixmap QPixmap::transformed(const QMatrix &matrix, Qt::TransformationMode mode) const
1535{
1536 return transformed(QTransform(matrix), mode);
1537}
1538
1539
1540
1541
1542
1543
1544
1545
1546/*!
1547 \class QPixmap
1548
1549 \brief The QPixmap class is an off-screen image representation
1550 that can be used as a paint device.
1551
1552 \ingroup painting
1553 \ingroup shared
1554
1555
1556 Qt provides four classes for handling image data: QImage, QPixmap,
1557 QBitmap and QPicture. QImage is designed and optimized for I/O,
1558 and for direct pixel access and manipulation, while QPixmap is
1559 designed and optimized for showing images on screen. QBitmap is
1560 only a convenience class that inherits QPixmap, ensuring a depth
1561 of 1. The isQBitmap() function returns true if a QPixmap object is
1562 really a bitmap, otherwise returns false. Finally, the QPicture class
1563 is a paint device that records and replays QPainter commands.
1564
1565 A QPixmap can easily be displayed on the screen using QLabel or
1566 one of QAbstractButton's subclasses (such as QPushButton and
1567 QToolButton). QLabel has a pixmap property, whereas
1568 QAbstractButton has an icon property.
1569
1570 In addition to the ordinary constructors, a QPixmap can be
1571 constructed using the static grabWidget() and grabWindow()
1572 functions which creates a QPixmap and paints the given widget, or
1573 window, into it.
1574
1575 QPixmap objects can be passed around by value since the QPixmap
1576 class uses implicit data sharing. For more information, see the \l
1577 {Implicit Data Sharing} documentation. QPixmap objects can also be
1578 streamed.
1579
1580 Depending on the system, QPixmap is stored using a RGB32 or a
1581 premultiplied alpha format. If the image has an alpha channel, and
1582 if the system allows, the preferred format is premultiplied alpha.
1583 Note also that QPixmap, unlike QImage, may be hardware dependent.
1584 On X11, Mac and Symbian, a QPixmap is stored on the server side while
1585 a QImage is stored on the client side (on Windows, these two classes
1586 have an equivalent internal representation, i.e. both QImage and
1587 QPixmap are stored on the client side and don't use any GDI
1588 resources).
1589
1590 Note that the pixel data in a pixmap is internal and is managed by
1591 the underlying window system. Because QPixmap is a QPaintDevice
1592 subclass, QPainter can be used to draw directly onto pixmaps.
1593 Pixels can only be accessed through QPainter functions or by
1594 converting the QPixmap to a QImage. However, the fill() function
1595 is available for initializing the entire pixmap with a given color.
1596
1597 There are functions to convert between QImage and
1598 QPixmap. Typically, the QImage class is used to load an image
1599 file, optionally manipulating the image data, before the QImage
1600 object is converted into a QPixmap to be shown on
1601 screen. Alternatively, if no manipulation is desired, the image
1602 file can be loaded directly into a QPixmap. On Windows, the
1603 QPixmap class also supports conversion between \c HBITMAP and
1604 QPixmap. On Symbian, the QPixmap class also supports conversion
1605 between CFbsBitmap and QPixmap.
1606
1607 QPixmap provides a collection of functions that can be used to
1608 obtain a variety of information about the pixmap. In addition,
1609 there are several functions that enables transformation of the
1610 pixmap.
1611
1612 \tableofcontents
1613
1614 \section1 Reading and Writing Image Files
1615
1616 QPixmap provides several ways of reading an image file: The file
1617 can be loaded when constructing the QPixmap object, or by using
1618 the load() or loadFromData() functions later on. When loading an
1619 image, the file name can either refer to an actual file on disk or
1620 to one of the application's embedded resources. See \l{The Qt
1621 Resource System} overview for details on how to embed images and
1622 other resource files in the application's executable.
1623
1624 Simply call the save() function to save a QPixmap object.
1625
1626 The complete list of supported file formats are available through
1627 the QImageReader::supportedImageFormats() and
1628 QImageWriter::supportedImageFormats() functions. New file formats
1629 can be added as plugins. By default, Qt supports the following
1630 formats:
1631
1632 \table
1633 \header \o Format \o Description \o Qt's support
1634 \row \o BMP \o Windows Bitmap \o Read/write
1635 \row \o GIF \o Graphic Interchange Format (optional) \o Read
1636 \row \o JPG \o Joint Photographic Experts Group \o Read/write
1637 \row \o JPEG \o Joint Photographic Experts Group \o Read/write
1638 \row \o PNG \o Portable Network Graphics \o Read/write
1639 \row \o PBM \o Portable Bitmap \o Read
1640 \row \o PGM \o Portable Graymap \o Read
1641 \row \o PPM \o Portable Pixmap \o Read/write
1642 \row \o XBM \o X11 Bitmap \o Read/write
1643 \row \o XPM \o X11 Pixmap \o Read/write
1644 \endtable
1645
1646 \section1 Pixmap Information
1647
1648 QPixmap provides a collection of functions that can be used to
1649 obtain a variety of information about the pixmap:
1650
1651 \table
1652 \header
1653 \o \o Available Functions
1654 \row
1655 \o Geometry
1656 \o
1657 The size(), width() and height() functions provide information
1658 about the pixmap's size. The rect() function returns the image's
1659 enclosing rectangle.
1660
1661 \row
1662 \o Alpha component
1663 \o
1664
1665 The hasAlphaChannel() returns true if the pixmap has a format that
1666 respects the alpha channel, otherwise returns false. The hasAlpha(),
1667 setMask() and mask() functions are legacy and should not be used.
1668 They are potentially very slow.
1669
1670 The createHeuristicMask() function creates and returns a 1-bpp
1671 heuristic mask (i.e. a QBitmap) for this pixmap. It works by
1672 selecting a color from one of the corners and then chipping away
1673 pixels of that color, starting at all the edges. The
1674 createMaskFromColor() function creates and returns a mask (i.e. a
1675 QBitmap) for the pixmap based on a given color.
1676
1677 \row
1678 \o Low-level information
1679 \o
1680
1681 The depth() function returns the depth of the pixmap. The
1682 defaultDepth() function returns the default depth, i.e. the depth
1683 used by the application on the given screen.
1684
1685 The cacheKey() function returns a number that uniquely
1686 identifies the contents of the QPixmap object.
1687
1688 The x11Info() function returns information about the configuration
1689 of the X display used by the screen to which the pixmap currently
1690 belongs. The x11PictureHandle() function returns the X11 Picture
1691 handle of the pixmap for XRender support. Note that the two latter
1692 functions are only available on x11.
1693
1694 \endtable
1695
1696 \section1 Pixmap Conversion
1697
1698 A QPixmap object can be converted into a QImage using the
1699 toImage() function. Likewise, a QImage can be converted into a
1700 QPixmap using the fromImage(). If this is too expensive an
1701 operation, you can use QBitmap::fromImage() instead.
1702
1703 In addition, on Windows, the QPixmap class supports conversion to
1704 and from HBITMAP: the toWinHBITMAP() function creates a HBITMAP
1705 equivalent to the QPixmap, based on the given HBitmapFormat, and
1706 returns the HBITMAP handle. The fromWinHBITMAP() function returns
1707 a QPixmap that is equivalent to the given bitmap which has the
1708 specified format. The QPixmap class also supports conversion to
1709 and from HICON: the toWinHICON() function creates a HICON equivalent
1710 to the QPixmap, and returns the HICON handle. The fromWinHICON()
1711 function returns a QPixmap that is equivalent to the given icon.
1712
1713 In addition, on Symbian, the QPixmap class supports conversion to
1714 and from CFbsBitmap: the toSymbianCFbsBitmap() function creates
1715 CFbsBitmap equivalent to the QPixmap, based on given mode and returns
1716 a CFbsBitmap object. The fromSymbianCFbsBitmap() function returns a
1717 QPixmap that is equivalent to the given bitmap and given mode.
1718
1719 \section1 Pixmap Transformations
1720
1721 QPixmap supports a number of functions for creating a new pixmap
1722 that is a transformed version of the original:
1723
1724 The scaled(), scaledToWidth() and scaledToHeight() functions
1725 return scaled copies of the pixmap, while the copy() function
1726 creates a QPixmap that is a plain copy of the original one.
1727
1728 The transformed() function returns a copy of the pixmap that is
1729 transformed with the given transformation matrix and
1730 transformation mode: Internally, the transformation matrix is
1731 adjusted to compensate for unwanted translation,
1732 i.e. transformed() returns the smallest pixmap containing all
1733 transformed points of the original pixmap. The static trueMatrix()
1734 function returns the actual matrix used for transforming the
1735 pixmap.
1736
1737 \sa QBitmap, QImage, QImageReader, QImageWriter
1738*/
1739
1740
1741/*!
1742 \typedef QPixmap::DataPtr
1743 \internal
1744*/
1745
1746/*!
1747 \fn DataPtr &QPixmap::data_ptr()
1748 \internal
1749*/
1750
1751/*!
1752 Returns true if this pixmap has an alpha channel, \e or has a
1753 mask, otherwise returns false.
1754
1755 \warning This is potentially an expensive operation.
1756
1757 \sa hasAlphaChannel(), mask()
1758*/
1759bool QPixmap::hasAlpha() const
1760{
1761 return data && (data->hasAlphaChannel() || !data->mask().isNull());
1762}
1763
1764/*!
1765 Returns true if the pixmap has a format that respects the alpha
1766 channel, otherwise returns false.
1767
1768 \sa hasAlpha()
1769*/
1770bool QPixmap::hasAlphaChannel() const
1771{
1772 return data && data->hasAlphaChannel();
1773}
1774
1775/*!
1776 \internal
1777*/
1778int QPixmap::metric(PaintDeviceMetric metric) const
1779{
1780 return data ? data->metric(metric) : 0;
1781}
1782
1783/*!
1784 \fn void QPixmap::setAlphaChannel(const QPixmap &alphaChannel)
1785 \obsolete
1786
1787 Sets the alpha channel of this pixmap to the given \a alphaChannel
1788 by converting the \a alphaChannel into 32 bit and using the
1789 intensity of the RGB pixel values.
1790
1791 The effect of this function is undefined when the pixmap is being
1792 painted on.
1793
1794 \warning This is potentially an expensive operation. Most usecases
1795 for this function are covered by QPainter and compositionModes
1796 which will normally execute faster.
1797
1798 \sa alphaChannel(), {QPixmap#Pixmap Transformations}{Pixmap
1799 Transformations}
1800 */
1801void QPixmap::setAlphaChannel(const QPixmap &alphaChannel)
1802{
1803 if (alphaChannel.isNull())
1804 return;
1805
1806 if (paintingActive()) {
1807 qWarning("QPixmap::setAlphaChannel: "
1808 "Cannot set alpha channel while pixmap is being painted on");
1809 return;
1810 }
1811
1812 if (width() != alphaChannel.width() && height() != alphaChannel.height()) {
1813 qWarning("QPixmap::setAlphaChannel: "
1814 "The pixmap and the alpha channel pixmap must have the same size");
1815 return;
1816 }
1817
1818 detach();
1819 data->setAlphaChannel(alphaChannel);
1820}
1821
1822/*!
1823 \obsolete
1824
1825 Returns the alpha channel of the pixmap as a new grayscale QPixmap in which
1826 each pixel's red, green, and blue values are given the alpha value of the
1827 original pixmap. The color depth of the returned pixmap is the system depth
1828 on X11 and 8-bit on Windows and Mac OS X.
1829
1830 You can use this function while debugging
1831 to get a visible image of the alpha channel. If the pixmap doesn't have an
1832 alpha channel, i.e., the alpha channel's value for all pixels equals
1833 0xff), a null pixmap is returned. You can check this with the \c isNull()
1834 function.
1835
1836 We show an example:
1837
1838 \snippet doc/src/snippets/alphachannel.cpp 0
1839
1840 \image alphachannelimage.png The pixmap and channelImage QPixmaps
1841
1842 \warning This is an expensive operation. The alpha channel of the
1843 pixmap is extracted dynamically from the pixeldata. Most usecases of this
1844 function are covered by QPainter and compositionModes which will normally
1845 execute faster.
1846
1847 \sa setAlphaChannel(), {QPixmap#Pixmap Information}{Pixmap
1848 Information}
1849*/
1850QPixmap QPixmap::alphaChannel() const
1851{
1852 return data ? data->alphaChannel() : QPixmap();
1853}
1854
1855/*!
1856 \internal
1857*/
1858QPaintEngine *QPixmap::paintEngine() const
1859{
1860 return data ? data->paintEngine() : 0;
1861}
1862
1863/*!
1864 \fn QBitmap QPixmap::mask() const
1865
1866 Extracts a bitmap mask from the pixmap's alpha channel.
1867
1868 \warning This is potentially an expensive operation. The mask of
1869 the pixmap is extracted dynamically from the pixeldata.
1870
1871 \sa setMask(), {QPixmap#Pixmap Information}{Pixmap Information}
1872*/
1873QBitmap QPixmap::mask() const
1874{
1875 return data ? data->mask() : QBitmap();
1876}
1877
1878/*!
1879 Returns the default pixmap depth used by the application.
1880
1881 On Windows and Mac, the default depth is always 32. On X11 and
1882 embedded, the depth of the screen will be returned by this
1883 function.
1884
1885 \sa depth(), QColormap::depth(), {QPixmap#Pixmap Information}{Pixmap Information}
1886
1887*/
1888int QPixmap::defaultDepth()
1889{
1890#if defined(Q_WS_QWS)
1891 return QScreen::instance()->depth();
1892#elif defined(Q_WS_X11)
1893 return QX11Info::appDepth();
1894#elif defined(Q_WS_WINCE)
1895 return QColormap::instance().depth();
1896#elif defined(Q_WS_WIN)
1897 return 32; // XXX
1898#elif defined(Q_WS_PM)
1899 return 32; // @todo check this
1900#elif defined(Q_WS_MAC)
1901 return 32;
1902#elif defined(Q_OS_SYMBIAN)
1903 return S60->screenDepth;
1904#endif
1905}
1906
1907/*!
1908 Detaches the pixmap from shared pixmap data.
1909
1910 A pixmap is automatically detached by Qt whenever its contents are
1911 about to change. This is done in almost all QPixmap member
1912 functions that modify the pixmap (fill(), fromImage(),
1913 load(), etc.), and in QPainter::begin() on a pixmap.
1914
1915 There are two exceptions in which detach() must be called
1916 explicitly, that is when calling the handle() or the
1917 x11PictureHandle() function (only available on X11). Otherwise,
1918 any modifications done using system calls, will be performed on
1919 the shared data.
1920
1921 The detach() function returns immediately if there is just a
1922 single reference or if the pixmap has not been initialized yet.
1923*/
1924void QPixmap::detach()
1925{
1926 if (!data)
1927 return;
1928
1929 QPixmapData::ClassId id = data->classId();
1930 if (id == QPixmapData::RasterClass) {
1931 QRasterPixmapData *rasterData = static_cast<QRasterPixmapData*>(data.data());
1932 rasterData->image.detach();
1933 }
1934
1935 if (data->is_cached && data->ref == 1)
1936 QImagePixmapCleanupHooks::executePixmapDataModificationHooks(data.data());
1937
1938#if defined(Q_WS_MAC)
1939 QMacPixmapData *macData = id == QPixmapData::MacClass ? static_cast<QMacPixmapData*>(data.data()) : 0;
1940 if (macData) {
1941 if (macData->cg_mask) {
1942 CGImageRelease(macData->cg_mask);
1943 macData->cg_mask = 0;
1944 }
1945 }
1946#endif
1947
1948 if (data->ref != 1) {
1949 *this = copy();
1950 }
1951 ++data->detach_no;
1952
1953#if defined(Q_WS_X11)
1954 if (data->classId() == QPixmapData::X11Class) {
1955 QX11PixmapData *d = static_cast<QX11PixmapData*>(data.data());
1956 d->flags &= ~QX11PixmapData::Uninitialized;
1957
1958 // reset the cache data
1959 if (d->hd2) {
1960 XFreePixmap(X11->display, d->hd2);
1961 d->hd2 = 0;
1962 }
1963 }
1964#elif defined(Q_WS_MAC)
1965 if (macData) {
1966 macData->macReleaseCGImageRef();
1967 macData->uninit = false;
1968 }
1969#endif
1970}
1971
1972/*!
1973 \fn QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1974
1975 Converts the given \a image to a pixmap using the specified \a
1976 flags to control the conversion. The \a flags argument is a
1977 bitwise-OR of the \l{Qt::ImageConversionFlags}. Passing 0 for \a
1978 flags sets all the default options.
1979
1980 In case of monochrome and 8-bit images, the image is first
1981 converted to a 32-bit pixmap and then filled with the colors in
1982 the color table. If this is too expensive an operation, you can
1983 use QBitmap::fromImage() instead.
1984
1985 \sa toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
1986*/
1987QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1988{
1989 if (image.isNull())
1990 return QPixmap();
1991
1992 QGraphicsSystem* gs = QApplicationPrivate::graphicsSystem();
1993 QScopedPointer<QPixmapData> data(gs ? gs->createPixmapData(QPixmapData::PixmapType)
1994 : QGraphicsSystem::createDefaultPixmapData(QPixmapData::PixmapType));
1995 data->fromImage(image, flags);
1996 return QPixmap(data.take());
1997}
1998
1999/*!
2000 \fn QPixmap QPixmap::grabWindow(WId window, int x, int y, int
2001 width, int height)
2002
2003 Creates and returns a pixmap constructed by grabbing the contents
2004 of the given \a window restricted by QRect(\a x, \a y, \a width,
2005 \a height).
2006
2007 The arguments (\a{x}, \a{y}) specify the offset in the window,
2008 whereas (\a{width}, \a{height}) specify the area to be copied. If
2009 \a width is negative, the function copies everything to the right
2010 border of the window. If \a height is negative, the function
2011 copies everything to the bottom of the window.
2012
2013 The window system identifier (\c WId) can be retrieved using the
2014 QWidget::winId() function. The rationale for using a window
2015 identifier and not a QWidget, is to enable grabbing of windows
2016 that are not part of the application, window system frames, and so
2017 on.
2018
2019 The grabWindow() function grabs pixels from the screen, not from
2020 the window, i.e. if there is another window partially or entirely
2021 over the one you grab, you get pixels from the overlying window,
2022 too. The mouse cursor is generally not grabbed.
2023
2024 Note on X11 that if the given \a window doesn't have the same depth
2025 as the root window, and another window partially or entirely
2026 obscures the one you grab, you will \e not get pixels from the
2027 overlying window. The contents of the obscured areas in the
2028 pixmap will be undefined and uninitialized.
2029
2030 On Windows Vista and above grabbing a layered window, which is
2031 created by setting the Qt::WA_TranslucentBackground attribute, will
2032 not work. Instead grabbing the desktop widget should work.
2033
2034 \warning In general, grabbing an area outside the screen is not
2035 safe. This depends on the underlying window system.
2036
2037 \sa grabWidget(), {Screenshot Example}
2038*/
2039
2040/*!
2041 \internal
2042*/
2043QPixmapData* QPixmap::pixmapData() const
2044{
2045 return data.data();
2046}
2047
2048/*!
2049 \enum QPixmap::HBitmapFormat
2050
2051 \bold{Win32 only:} This enum defines how the conversion between \c
2052 HBITMAP and QPixmap is performed.
2053
2054 \warning This enum is only available on Windows.
2055
2056 \value NoAlpha The alpha channel is ignored and always treated as
2057 being set to fully opaque. This is preferred if the \c HBITMAP is
2058 used with standard GDI calls, such as \c BitBlt().
2059
2060 \value PremultipliedAlpha The \c HBITMAP is treated as having an
2061 alpha channel and premultiplied colors. This is preferred if the
2062 \c HBITMAP is accessed through the \c AlphaBlend() GDI function.
2063
2064 \value Alpha The \c HBITMAP is treated as having a plain alpha
2065 channel. This is the preferred format if the \c HBITMAP is going
2066 to be used as an application icon or systray icon.
2067
2068 \sa fromWinHBITMAP(), toWinHBITMAP()
2069*/
2070
2071/*! \fn HBITMAP QPixmap::toWinHBITMAP(HBitmapFormat format) const
2072 \bold{Win32 only:} Creates a \c HBITMAP equivalent to the QPixmap,
2073 based on the given \a format. Returns the \c HBITMAP handle.
2074
2075 It is the caller's responsibility to free the \c HBITMAP data
2076 after use.
2077
2078 \warning This function is only available on Windows.
2079
2080 \sa fromWinHBITMAP(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2081*/
2082
2083/*! \fn QPixmap QPixmap::fromWinHBITMAP(HBITMAP bitmap, HBitmapFormat format)
2084 \bold{Win32 only:} Returns a QPixmap that is equivalent to the
2085 given \a bitmap. The conversion is based on the specified \a
2086 format.
2087
2088 \warning This function is only available on Windows.
2089
2090 \sa toWinHBITMAP(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2091
2092*/
2093
2094/*! \fn HICON QPixmap::toWinHICON() const
2095 \since 4.6
2096
2097 \bold{Win32 only:} Creates a \c HICON equivalent to the QPixmap.
2098 Returns the \c HICON handle.
2099
2100 It is the caller's responsibility to free the \c HICON data after use.
2101
2102 \warning This function is only available on Windows.
2103
2104 \sa fromWinHICON(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2105*/
2106
2107/*! \fn QPixmap QPixmap::fromWinHICON(HICON icon)
2108 \since 4.6
2109
2110 \bold{Win32 only:} Returns a QPixmap that is equivalent to the given
2111 \a icon.
2112
2113 \warning This function is only available on Windows.
2114
2115 \sa toWinHICON(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2116
2117*/
2118
2119/*! \fn const QX11Info &QPixmap::x11Info() const
2120 \bold{X11 only:} Returns information about the configuration of
2121 the X display used by the screen to which the pixmap currently belongs.
2122
2123 \warning This function is only available on X11.
2124
2125 \sa {QPixmap#Pixmap Information}{Pixmap Information}
2126*/
2127
2128/*! \fn Qt::HANDLE QPixmap::x11PictureHandle() const
2129 \bold{X11 only:} Returns the X11 Picture handle of the pixmap for
2130 XRender support.
2131
2132 This function will return 0 if XRender support is not compiled
2133 into Qt, if the XRender extension is not supported on the X11
2134 display, or if the handle could not be created. Use of this
2135 function is not portable.
2136
2137 \warning This function is only available on X11.
2138
2139 \sa {QPixmap#Pixmap Information}{Pixmap Information}
2140*/
2141
2142/*! \fn int QPixmap::x11SetDefaultScreen(int screen)
2143 \internal
2144*/
2145
2146/*! \fn void QPixmap::x11SetScreen(int screen)
2147 \internal
2148*/
2149
2150/*! \fn QRgb* QPixmap::clut() const
2151 \internal
2152*/
2153
2154/*! \fn int QPixmap::numCols() const
2155 \obsolete
2156 \internal
2157 \sa colorCount()
2158*/
2159
2160/*! \fn int QPixmap::colorCount() const
2161 \since 4.6
2162 \internal
2163*/
2164
2165/*! \fn const uchar* QPixmap::qwsBits() const
2166 \internal
2167 \since 4.1
2168*/
2169
2170/*! \fn int QPixmap::qwsBytesPerLine() const
2171 \internal
2172 \since 4.1
2173*/
2174
2175QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.