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

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

trunk: Merged in qt 4.6.2 sources.

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 bool ok;
835
836 if (data) {
837 ok = data->fromFile(fileName, format, flags);
838 } else {
839 QScopedPointer<QPixmapData> tmp(QPixmapData::create(0, 0, QPixmapData::PixmapType));
840 ok = tmp->fromFile(fileName, format, flags);
841 if (ok)
842 data = tmp.take();
843 }
844
845 if (ok)
846 QPixmapCache::insert(key, *this);
847
848 return ok;
849}
850
851/*!
852 \fn bool QPixmap::loadFromData(const uchar *data, uint len, const char *format, Qt::ImageConversionFlags flags)
853
854 Loads a pixmap from the \a len first bytes of the given binary \a
855 data. Returns true if the pixmap was loaded successfully;
856 otherwise returns false.
857
858 The loader attempts to read the pixmap using the specified \a
859 format. If the \a format is not specified (which is the default),
860 the loader probes the file for a header to guess the file format.
861
862 If the data needs to be modified to fit in a lower-resolution
863 result (e.g. converting from 32-bit to 8-bit), use the \a flags to
864 control the conversion.
865
866 \sa load(), {QPixmap#Reading and Writing Image Files}{Reading and
867 Writing Image Files}
868*/
869
870bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, Qt::ImageConversionFlags flags)
871{
872 if (len == 0 || buf == 0)
873 return false;
874
875 if (!data)
876 data = QPixmapData::create(0, 0, QPixmapData::PixmapType);
877
878 return data->fromData(buf, len, format, flags);
879}
880
881/*!
882 \fn bool QPixmap::loadFromData(const QByteArray &data, const char *format, Qt::ImageConversionFlags flags)
883
884 \overload
885
886 Loads a pixmap from the binary \a data using the specified \a
887 format and conversion \a flags.
888*/
889
890
891/*!
892 Saves the pixmap to the file with the given \a fileName using the
893 specified image file \a format and \a quality factor. Returns true
894 if successful; otherwise returns false.
895
896 The \a quality factor must be in the range [0,100] or -1. Specify
897 0 to obtain small compressed files, 100 for large uncompressed
898 files, and -1 to use the default settings.
899
900 If \a format is 0, an image format will be chosen from \a fileName's
901 suffix.
902
903 \sa {QPixmap#Reading and Writing Image Files}{Reading and Writing
904 Image Files}
905*/
906
907bool QPixmap::save(const QString &fileName, const char *format, int quality) const
908{
909 if (isNull())
910 return false; // nothing to save
911 QImageWriter writer(fileName, format);
912 return doImageIO(&writer, quality);
913}
914
915/*!
916 \overload
917
918 This function writes a QPixmap to the given \a device using the
919 specified image file \a format and \a quality factor. This can be
920 used, for example, to save a pixmap directly into a QByteArray:
921
922 \snippet doc/src/snippets/image/image.cpp 1
923*/
924
925bool QPixmap::save(QIODevice* device, const char* format, int quality) const
926{
927 if (isNull())
928 return false; // nothing to save
929 QImageWriter writer(device, format);
930 return doImageIO(&writer, quality);
931}
932
933/*! \internal
934*/
935bool QPixmap::doImageIO(QImageWriter *writer, int quality) const
936{
937 if (quality > 100 || quality < -1)
938 qWarning("QPixmap::save: quality out of range [-1,100]");
939 if (quality >= 0)
940 writer->setQuality(qMin(quality,100));
941 return writer->write(toImage());
942}
943
944
945// The implementation (and documentation) of
946// QPixmap::fill(const QWidget *, const QPoint &)
947// is in qwidget.cpp
948
949/*!
950 \fn void QPixmap::fill(const QWidget *widget, int x, int y)
951 \overload
952
953 Fills the pixmap with the \a widget's background color or pixmap.
954 The given point, (\a x, \a y), defines an offset in widget
955 coordinates to which the pixmap's top-left pixel will be mapped
956 to.
957*/
958
959/*!
960 Fills the pixmap with the given \a color.
961
962 The effect of this function is undefined when the pixmap is
963 being painted on.
964
965 \sa {QPixmap#Pixmap Transformations}{Pixmap Transformations}
966*/
967
968void QPixmap::fill(const QColor &color)
969{
970 if (isNull())
971 return;
972
973 // Some people are probably already calling fill while a painter is active, so to not break
974 // their programs, only print a warning and return when the fill operation could cause a crash.
975 if (paintingActive() && (color.alpha() != 255) && !hasAlphaChannel()) {
976 qWarning("QPixmap::fill: Cannot fill while pixmap is being painted on");
977 return;
978 }
979
980 if (data->ref == 1) {
981 // detach() will also remove this pixmap from caches, so
982 // it has to be called even when ref == 1.
983 detach();
984 } else {
985 // Don't bother to make a copy of the data object, since
986 // it will be filled with new pixel data anyway.
987 QPixmapData *d = data->createCompatiblePixmapData();
988 d->resize(data->width(), data->height());
989 data = d;
990 }
991 data->fill(color);
992}
993
994/*! \obsolete
995 Returns a number that identifies the contents of this QPixmap
996 object. Distinct QPixmap objects can only have the same serial
997 number if they refer to the same contents (but they don't have
998 to).
999
1000 Use cacheKey() instead.
1001
1002 \warning The serial number doesn't necessarily change when
1003 the pixmap is altered. This means that it may be dangerous to use
1004 it as a cache key. For caching pixmaps, we recommend using the
1005 QPixmapCache class whenever possible.
1006*/
1007int QPixmap::serialNumber() const
1008{
1009 if (isNull())
1010 return 0;
1011 return data->serialNumber();
1012}
1013
1014/*!
1015 Returns a number that identifies this QPixmap. Distinct QPixmap
1016 objects can only have the same cache key if they refer to the same
1017 contents.
1018
1019 The cacheKey() will change when the pixmap is altered.
1020*/
1021qint64 QPixmap::cacheKey() const
1022{
1023 if (isNull())
1024 return 0;
1025
1026 Q_ASSERT(data);
1027 return data->cacheKey();
1028}
1029
1030static void sendResizeEvents(QWidget *target)
1031{
1032 QResizeEvent e(target->size(), QSize());
1033 QApplication::sendEvent(target, &e);
1034
1035 const QObjectList children = target->children();
1036 for (int i = 0; i < children.size(); ++i) {
1037 QWidget *child = static_cast<QWidget*>(children.at(i));
1038 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
1039 sendResizeEvents(child);
1040 }
1041}
1042
1043/*!
1044 \fn QPixmap QPixmap::grabWidget(QWidget * widget, const QRect &rectangle)
1045
1046 Creates a pixmap and paints the given \a widget, restricted by the
1047 given \a rectangle, in it. If the \a widget has any children, then
1048 they are also painted in the appropriate positions.
1049
1050 If no rectangle is specified (the default) the entire widget is
1051 painted.
1052
1053 If \a widget is 0, the specified rectangle doesn't overlap the
1054 widget's rectangle, or an error occurs, the function will return a
1055 null QPixmap. If the rectangle is a superset of the given \a
1056 widget, the areas outside the \a widget are covered with the
1057 widget's background.
1058
1059 This function actually asks \a widget to paint itself (and its
1060 children to paint themselves) by calling paintEvent() with painter
1061 redirection turned on. But QPixmap also provides the grabWindow()
1062 function which is a bit faster by grabbing pixels directly off the
1063 screen. In addition, if there are overlaying windows,
1064 grabWindow(), unlike grabWidget(), will see them.
1065
1066 \warning Do not grab a widget from its QWidget::paintEvent().
1067 However, it is safe to grab a widget from another widget's
1068 \l {QWidget::}{paintEvent()}.
1069
1070 \sa grabWindow()
1071*/
1072
1073QPixmap QPixmap::grabWidget(QWidget * widget, const QRect &rect)
1074{
1075 if (!widget)
1076 return QPixmap();
1077
1078 if (widget->testAttribute(Qt::WA_PendingResizeEvent) || !widget->testAttribute(Qt::WA_WState_Created))
1079 sendResizeEvents(widget);
1080
1081 QRect r(rect);
1082 if (r.width() < 0)
1083 r.setWidth(widget->width() - rect.x());
1084 if (r.height() < 0)
1085 r.setHeight(widget->height() - rect.y());
1086
1087 if (!r.intersects(widget->rect()))
1088 return QPixmap();
1089
1090 QPixmap res(r.size());
1091 widget->render(&res, QPoint(), r,
1092 QWidget::DrawWindowBackground | QWidget::DrawChildren | QWidget::IgnoreMask);
1093 return res;
1094}
1095
1096/*!
1097 \fn QPixmap QPixmap::grabWidget(QWidget *widget, int x, int y, int
1098 width, int height)
1099
1100 \overload
1101
1102 Creates a pixmap and paints the given \a widget, restricted by
1103 QRect(\a x, \a y, \a width, \a height), in it.
1104
1105 \warning Do not grab a widget from its QWidget::paintEvent().
1106 However, it is safe to grab a widget from another widget's
1107 \l {QWidget::}{paintEvent()}.
1108*/
1109
1110
1111/*!
1112 \since 4.5
1113
1114 \enum QPixmap::ShareMode
1115
1116 This enum type defines the share modes that are available when
1117 creating a QPixmap object from a raw X11 Pixmap handle.
1118
1119 \value ImplicitlyShared This mode will cause the QPixmap object to
1120 create a copy of the internal data before it is modified, thus
1121 keeping the original X11 pixmap intact.
1122
1123 \value ExplicitlyShared In this mode, the pixmap data will \e not be
1124 copied before it is modified, which in effect will change the
1125 original X11 pixmap.
1126
1127 \warning This enum is only used for X11 specific functions; using
1128 it is non-portable.
1129
1130 \sa QPixmap::fromX11Pixmap()
1131*/
1132
1133/*!
1134 \since 4.5
1135
1136 \fn QPixmap QPixmap::fromX11Pixmap(Qt::HANDLE pixmap, QPixmap::ShareMode mode)
1137
1138 Creates a QPixmap from the native X11 Pixmap handle \a pixmap,
1139 using \a mode as the share mode. The default share mode is
1140 QPixmap::ImplicitlyShared, which means that a copy of the pixmap is
1141 made if someone tries to modify it by e.g. drawing onto it.
1142
1143 QPixmap does \e not take ownership of the \a pixmap handle, and
1144 have to be deleted by the user.
1145
1146 \warning This function is X11 specific; using it is non-portable.
1147
1148 \sa QPixmap::ShareMode
1149*/
1150
1151
1152#if defined(Q_WS_X11) || defined(Q_WS_QWS)
1153
1154/*!
1155 Returns the pixmap's handle to the device context.
1156
1157 Note that, since QPixmap make use of \l {Implicit Data
1158 Sharing}{implicit data sharing}, the detach() function must be
1159 called explicitly to ensure that only \e this pixmap's data is
1160 modified if the pixmap data is shared.
1161
1162 \warning This function is X11 specific; using it is non-portable.
1163
1164 \sa detach()
1165*/
1166
1167Qt::HANDLE QPixmap::handle() const
1168{
1169#if defined(Q_WS_X11)
1170 if (data && data->classId() == QPixmapData::X11Class)
1171 return static_cast<const QX11PixmapData*>(data.constData())->handle();
1172#endif
1173 return 0;
1174}
1175#endif
1176
1177
1178#ifdef QT3_SUPPORT
1179static Qt::ImageConversionFlags colorModeToFlags(QPixmap::ColorMode mode)
1180{
1181 Qt::ImageConversionFlags flags = Qt::AutoColor;
1182 switch (mode) {
1183 case QPixmap::Color:
1184 flags |= Qt::ColorOnly;
1185 break;
1186 case QPixmap::Mono:
1187 flags |= Qt::MonoOnly;
1188 break;
1189 default:
1190 break;// Nothing.
1191 }
1192 return flags;
1193}
1194
1195/*!
1196 Use the constructor that takes a Qt::ImageConversionFlag instead.
1197*/
1198
1199QPixmap::QPixmap(const QString& fileName, const char *format, ColorMode mode)
1200 : QPaintDevice()
1201{
1202 init(0, 0, QPixmapData::PixmapType);
1203 if (!qt_pixmap_thread_test())
1204 return;
1205
1206 load(fileName, format, colorModeToFlags(mode));
1207}
1208
1209/*!
1210 Constructs a pixmap from the QImage \a image.
1211
1212 Use the static fromImage() function instead.
1213*/
1214QPixmap::QPixmap(const QImage& image)
1215 : QPaintDevice()
1216{
1217 init(0, 0, QPixmapData::PixmapType);
1218 if (!qt_pixmap_thread_test())
1219 return;
1220
1221 if (data && data->pixelType() == QPixmapData::BitmapType)
1222 *this = QBitmap::fromImage(image);
1223 else
1224 *this = fromImage(image);
1225}
1226
1227/*!
1228 \overload
1229
1230 Converts the given \a image to a pixmap that is assigned to this
1231 pixmap.
1232
1233 Use the static fromImage() function instead.
1234*/
1235
1236QPixmap &QPixmap::operator=(const QImage &image)
1237{
1238 if (data && data->pixelType() == QPixmapData::BitmapType)
1239 *this = QBitmap::fromImage(image);
1240 else
1241 *this = fromImage(image);
1242 return *this;
1243}
1244
1245/*!
1246 Use the load() function that takes a Qt::ImageConversionFlag instead.
1247*/
1248
1249bool QPixmap::load(const QString &fileName, const char *format, ColorMode mode)
1250{
1251 return load(fileName, format, colorModeToFlags(mode));
1252}
1253
1254/*!
1255 Use the loadFromData() function that takes a Qt::ImageConversionFlag instead.
1256*/
1257
1258bool QPixmap::loadFromData(const uchar *buf, uint len, const char *format, ColorMode mode)
1259{
1260 return loadFromData(buf, len, format, colorModeToFlags(mode));
1261}
1262
1263/*!
1264 Use the static fromImage() function instead.
1265*/
1266bool QPixmap::convertFromImage(const QImage &image, ColorMode mode)
1267{
1268 if (data && data->pixelType() == QPixmapData::BitmapType)
1269 *this = QBitmap::fromImage(image, colorModeToFlags(mode));
1270 else
1271 *this = fromImage(image, colorModeToFlags(mode));
1272 return !isNull();
1273}
1274
1275#endif
1276
1277/*****************************************************************************
1278 QPixmap stream functions
1279 *****************************************************************************/
1280#if !defined(QT_NO_DATASTREAM)
1281/*!
1282 \relates QPixmap
1283
1284 Writes the given \a pixmap to the given \a stream as a PNG
1285 image. Note that writing the stream to a file will not produce a
1286 valid image file.
1287
1288 \sa QPixmap::save(), {Format of the QDataStream Operators}
1289*/
1290
1291QDataStream &operator<<(QDataStream &stream, const QPixmap &pixmap)
1292{
1293 return stream << pixmap.toImage();
1294}
1295
1296/*!
1297 \relates QPixmap
1298
1299 Reads an image from the given \a stream into the given \a pixmap.
1300
1301 \sa QPixmap::load(), {Format of the QDataStream Operators}
1302*/
1303
1304QDataStream &operator>>(QDataStream &stream, QPixmap &pixmap)
1305{
1306 QImage image;
1307 stream >> image;
1308
1309 if (image.isNull()) {
1310 pixmap = QPixmap();
1311 } else if (image.depth() == 1) {
1312 pixmap = QBitmap::fromImage(image);
1313 } else {
1314 pixmap = QPixmap::fromImage(image);
1315 }
1316 return stream;
1317}
1318
1319#endif // QT_NO_DATASTREAM
1320
1321#ifdef QT3_SUPPORT
1322Q_GUI_EXPORT void copyBlt(QPixmap *dst, int dx, int dy,
1323 const QPixmap *src, int sx, int sy, int sw, int sh)
1324{
1325 Q_ASSERT_X(dst, "::copyBlt", "Destination pixmap must be non-null");
1326 Q_ASSERT_X(src, "::copyBlt", "Source pixmap must be non-null");
1327
1328 if (src->hasAlphaChannel()) {
1329 if (dst->paintEngine()->hasFeature(QPaintEngine::PorterDuff)) {
1330 QPainter p(dst);
1331 p.setCompositionMode(QPainter::CompositionMode_Source);
1332 p.drawPixmap(dx, dy, *src, sx, sy, sw, sh);
1333 } else {
1334 QImage image = dst->toImage().convertToFormat(QImage::Format_ARGB32_Premultiplied);
1335 QPainter p(&image);
1336 p.setCompositionMode(QPainter::CompositionMode_Source);
1337 p.drawPixmap(dx, dy, *src, sx, sy, sw, sh);
1338 p.end();
1339 *dst = QPixmap::fromImage(image);
1340 }
1341 } else {
1342 QPainter p(dst);
1343 p.drawPixmap(dx, dy, *src, sx, sy, sw, sh);
1344 }
1345
1346}
1347#endif
1348
1349/*!
1350 \internal
1351*/
1352
1353bool QPixmap::isDetached() const
1354{
1355 return data && data->ref == 1;
1356}
1357
1358/*! \internal
1359 ### Qt5 - remove me.
1360*/
1361void QPixmap::deref()
1362{
1363 Q_ASSERT_X(false, "QPixmap::deref()", "Do not call this function anymore!");
1364}
1365
1366/*!
1367 \fn QImage QPixmap::convertToImage() const
1368
1369 Use the toImage() function instead.
1370*/
1371
1372/*!
1373 \fn bool QPixmap::convertFromImage(const QImage &image, Qt::ImageConversionFlags flags)
1374
1375 Use the static fromImage() function instead.
1376*/
1377
1378/*!
1379 \fn QPixmap QPixmap::xForm(const QMatrix &matrix) const
1380
1381 Use transformed() instead.
1382*/
1383
1384/*!
1385 \fn QPixmap QPixmap::scaled(int width, int height,
1386 Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode
1387 transformMode) const
1388
1389 \overload
1390
1391 Returns a copy of the pixmap scaled to a rectangle with the given
1392 \a width and \a height according to the given \a aspectRatioMode and
1393 \a transformMode.
1394
1395 If either the \a width or the \a height is zero or negative, this
1396 function returns a null pixmap.
1397*/
1398
1399/*!
1400 \fn QPixmap QPixmap::scaled(const QSize &size, Qt::AspectRatioMode
1401 aspectRatioMode, Qt::TransformationMode transformMode) const
1402
1403 Scales the pixmap to the given \a size, using the aspect ratio and
1404 transformation modes specified by \a aspectRatioMode and \a
1405 transformMode.
1406
1407 \image qimage-scaling.png
1408
1409 \list
1410 \i If \a aspectRatioMode is Qt::IgnoreAspectRatio, the pixmap
1411 is scaled to \a size.
1412 \i If \a aspectRatioMode is Qt::KeepAspectRatio, the pixmap is
1413 scaled to a rectangle as large as possible inside \a size, preserving the aspect ratio.
1414 \i If \a aspectRatioMode is Qt::KeepAspectRatioByExpanding,
1415 the pixmap is scaled to a rectangle as small as possible
1416 outside \a size, preserving the aspect ratio.
1417 \endlist
1418
1419 If the given \a size is empty, this function returns a null
1420 pixmap.
1421
1422
1423 In some cases it can be more beneficial to draw the pixmap to a
1424 painter with a scale set rather than scaling the pixmap. This is
1425 the case when the painter is for instance based on OpenGL or when
1426 the scale factor changes rapidly.
1427
1428 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1429 Transformations}
1430
1431*/
1432QPixmap QPixmap::scaled(const QSize& s, Qt::AspectRatioMode aspectMode, Qt::TransformationMode mode) const
1433{
1434 if (isNull()) {
1435 qWarning("QPixmap::scaled: Pixmap is a null pixmap");
1436 return QPixmap();
1437 }
1438 if (s.isEmpty())
1439 return QPixmap();
1440
1441 QSize newSize = size();
1442 newSize.scale(s, aspectMode);
1443 if (newSize == size())
1444 return *this;
1445
1446 QTransform wm = QTransform::fromScale((qreal)newSize.width() / width(),
1447 (qreal)newSize.height() / height());
1448 QPixmap pix = transformed(wm, mode);
1449 return pix;
1450}
1451
1452/*!
1453 \fn QPixmap QPixmap::scaledToWidth(int width, Qt::TransformationMode
1454 mode) const
1455
1456 Returns a scaled copy of the image. The returned image is scaled
1457 to the given \a width using the specified transformation \a mode.
1458 The height of the pixmap is automatically calculated so that the
1459 aspect ratio of the pixmap is preserved.
1460
1461 If \a width is 0 or negative, a null pixmap is returned.
1462
1463 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1464 Transformations}
1465*/
1466QPixmap QPixmap::scaledToWidth(int w, Qt::TransformationMode mode) const
1467{
1468 if (isNull()) {
1469 qWarning("QPixmap::scaleWidth: Pixmap is a null pixmap");
1470 return copy();
1471 }
1472 if (w <= 0)
1473 return QPixmap();
1474
1475 qreal factor = (qreal) w / width();
1476 QTransform wm = QTransform::fromScale(factor, factor);
1477 return transformed(wm, mode);
1478}
1479
1480/*!
1481 \fn QPixmap QPixmap::scaledToHeight(int height,
1482 Qt::TransformationMode mode) const
1483
1484 Returns a scaled copy of the image. The returned image is scaled
1485 to the given \a height using the specified transformation \a mode.
1486 The width of the pixmap is automatically calculated so that the
1487 aspect ratio of the pixmap is preserved.
1488
1489 If \a height is 0 or negative, a null pixmap is returned.
1490
1491 \sa isNull(), {QPixmap#Pixmap Transformations}{Pixmap
1492 Transformations}
1493*/
1494QPixmap QPixmap::scaledToHeight(int h, Qt::TransformationMode mode) const
1495{
1496 if (isNull()) {
1497 qWarning("QPixmap::scaleHeight: Pixmap is a null pixmap");
1498 return copy();
1499 }
1500 if (h <= 0)
1501 return QPixmap();
1502
1503 qreal factor = (qreal) h / height();
1504 QTransform wm = QTransform::fromScale(factor, factor);
1505 return transformed(wm, mode);
1506}
1507
1508/*!
1509 Returns a copy of the pixmap that is transformed using the given
1510 transformation \a transform and transformation \a mode. The original
1511 pixmap is not changed.
1512
1513 The transformation \a transform is internally adjusted to compensate
1514 for unwanted translation; i.e. the pixmap produced is the smallest
1515 pixmap that contains all the transformed points of the original
1516 pixmap. Use the trueMatrix() function to retrieve the actual
1517 matrix used for transforming the pixmap.
1518
1519 This function is slow because it involves transformation to a
1520 QImage, non-trivial computations and a transformation back to a
1521 QPixmap.
1522
1523 \sa trueMatrix(), {QPixmap#Pixmap Transformations}{Pixmap
1524 Transformations}
1525*/
1526QPixmap QPixmap::transformed(const QTransform &transform,
1527 Qt::TransformationMode mode) const
1528{
1529 if (isNull() || transform.type() <= QTransform::TxTranslate)
1530 return *this;
1531
1532 return data->transformed(transform, mode);
1533}
1534
1535/*!
1536 \overload
1537
1538 This convenience function loads the \a matrix into a
1539 QTransform and calls the overloaded function.
1540 */
1541QPixmap QPixmap::transformed(const QMatrix &matrix, Qt::TransformationMode mode) const
1542{
1543 return transformed(QTransform(matrix), mode);
1544}
1545
1546
1547
1548
1549
1550
1551
1552
1553/*!
1554 \class QPixmap
1555
1556 \brief The QPixmap class is an off-screen image representation
1557 that can be used as a paint device.
1558
1559 \ingroup painting
1560 \ingroup shared
1561
1562
1563 Qt provides four classes for handling image data: QImage, QPixmap,
1564 QBitmap and QPicture. QImage is designed and optimized for I/O,
1565 and for direct pixel access and manipulation, while QPixmap is
1566 designed and optimized for showing images on screen. QBitmap is
1567 only a convenience class that inherits QPixmap, ensuring a depth
1568 of 1. The isQBitmap() function returns true if a QPixmap object is
1569 really a bitmap, otherwise returns false. Finally, the QPicture class
1570 is a paint device that records and replays QPainter commands.
1571
1572 A QPixmap can easily be displayed on the screen using QLabel or
1573 one of QAbstractButton's subclasses (such as QPushButton and
1574 QToolButton). QLabel has a pixmap property, whereas
1575 QAbstractButton has an icon property.
1576
1577 In addition to the ordinary constructors, a QPixmap can be
1578 constructed using the static grabWidget() and grabWindow()
1579 functions which creates a QPixmap and paints the given widget, or
1580 window, into it.
1581
1582 QPixmap objects can be passed around by value since the QPixmap
1583 class uses implicit data sharing. For more information, see the \l
1584 {Implicit Data Sharing} documentation. QPixmap objects can also be
1585 streamed.
1586
1587 Depending on the system, QPixmap is stored using a RGB32 or a
1588 premultiplied alpha format. If the image has an alpha channel, and
1589 if the system allows, the preferred format is premultiplied alpha.
1590 Note also that QPixmap, unlike QImage, may be hardware dependent.
1591 On X11, Mac and Symbian, a QPixmap is stored on the server side while
1592 a QImage is stored on the client side (on Windows, these two classes
1593 have an equivalent internal representation, i.e. both QImage and
1594 QPixmap are stored on the client side and don't use any GDI
1595 resources).
1596
1597 Note that the pixel data in a pixmap is internal and is managed by
1598 the underlying window system. Because QPixmap is a QPaintDevice
1599 subclass, QPainter can be used to draw directly onto pixmaps.
1600 Pixels can only be accessed through QPainter functions or by
1601 converting the QPixmap to a QImage. However, the fill() function
1602 is available for initializing the entire pixmap with a given color.
1603
1604 There are functions to convert between QImage and
1605 QPixmap. Typically, the QImage class is used to load an image
1606 file, optionally manipulating the image data, before the QImage
1607 object is converted into a QPixmap to be shown on
1608 screen. Alternatively, if no manipulation is desired, the image
1609 file can be loaded directly into a QPixmap. On Windows, the
1610 QPixmap class also supports conversion between \c HBITMAP and
1611 QPixmap. On Symbian, the QPixmap class also supports conversion
1612 between CFbsBitmap and QPixmap.
1613
1614 QPixmap provides a collection of functions that can be used to
1615 obtain a variety of information about the pixmap. In addition,
1616 there are several functions that enables transformation of the
1617 pixmap.
1618
1619 \tableofcontents
1620
1621 \section1 Reading and Writing Image Files
1622
1623 QPixmap provides several ways of reading an image file: The file
1624 can be loaded when constructing the QPixmap object, or by using
1625 the load() or loadFromData() functions later on. When loading an
1626 image, the file name can either refer to an actual file on disk or
1627 to one of the application's embedded resources. See \l{The Qt
1628 Resource System} overview for details on how to embed images and
1629 other resource files in the application's executable.
1630
1631 Simply call the save() function to save a QPixmap object.
1632
1633 The complete list of supported file formats are available through
1634 the QImageReader::supportedImageFormats() and
1635 QImageWriter::supportedImageFormats() functions. New file formats
1636 can be added as plugins. By default, Qt supports the following
1637 formats:
1638
1639 \table
1640 \header \o Format \o Description \o Qt's support
1641 \row \o BMP \o Windows Bitmap \o Read/write
1642 \row \o GIF \o Graphic Interchange Format (optional) \o Read
1643 \row \o JPG \o Joint Photographic Experts Group \o Read/write
1644 \row \o JPEG \o Joint Photographic Experts Group \o Read/write
1645 \row \o PNG \o Portable Network Graphics \o Read/write
1646 \row \o PBM \o Portable Bitmap \o Read
1647 \row \o PGM \o Portable Graymap \o Read
1648 \row \o PPM \o Portable Pixmap \o Read/write
1649 \row \o XBM \o X11 Bitmap \o Read/write
1650 \row \o XPM \o X11 Pixmap \o Read/write
1651 \endtable
1652
1653 \section1 Pixmap Information
1654
1655 QPixmap provides a collection of functions that can be used to
1656 obtain a variety of information about the pixmap:
1657
1658 \table
1659 \header
1660 \o \o Available Functions
1661 \row
1662 \o Geometry
1663 \o
1664 The size(), width() and height() functions provide information
1665 about the pixmap's size. The rect() function returns the image's
1666 enclosing rectangle.
1667
1668 \row
1669 \o Alpha component
1670 \o
1671
1672 The hasAlphaChannel() returns true if the pixmap has a format that
1673 respects the alpha channel, otherwise returns false, while the
1674 hasAlpha() function returns true if the pixmap has an alpha
1675 channel \e or a mask (otherwise false). The mask() function returns
1676 the mask as a QBitmap object, which can be set using setMask().
1677
1678 The createHeuristicMask() function creates and returns a 1-bpp
1679 heuristic mask (i.e. a QBitmap) for this pixmap. It works by
1680 selecting a color from one of the corners and then chipping away
1681 pixels of that color, starting at all the edges. The
1682 createMaskFromColor() function creates and returns a mask (i.e. a
1683 QBitmap) for the pixmap based on a given color.
1684
1685 \row
1686 \o Low-level information
1687 \o
1688
1689 The depth() function returns the depth of the pixmap. The
1690 defaultDepth() function returns the default depth, i.e. the depth
1691 used by the application on the given screen.
1692
1693 The cacheKey() function returns a number that uniquely
1694 identifies the contents of the QPixmap object.
1695
1696 The x11Info() function returns information about the configuration
1697 of the X display used by the screen to which the pixmap currently
1698 belongs. The x11PictureHandle() function returns the X11 Picture
1699 handle of the pixmap for XRender support. Note that the two latter
1700 functions are only available on x11.
1701
1702 \endtable
1703
1704 \section1 Pixmap Conversion
1705
1706 A QPixmap object can be converted into a QImage using the
1707 toImage() function. Likewise, a QImage can be converted into a
1708 QPixmap using the fromImage(). If this is too expensive an
1709 operation, you can use QBitmap::fromImage() instead.
1710
1711 In addition, on Windows, the QPixmap class supports conversion to
1712 and from HBITMAP: the toWinHBITMAP() function creates a HBITMAP
1713 equivalent to the QPixmap, based on the given HBitmapFormat, and
1714 returns the HBITMAP handle. The fromWinHBITMAP() function returns
1715 a QPixmap that is equivalent to the given bitmap which has the
1716 specified format. The QPixmap class also supports conversion to
1717 and from HICON: the toWinHICON() function creates a HICON equivalent
1718 to the QPixmap, and returns the HICON handle. The fromWinHICON()
1719 function returns a QPixmap that is equivalent to the given icon.
1720
1721 In addition, on Symbian, the QPixmap class supports conversion to
1722 and from CFbsBitmap: the toSymbianCFbsBitmap() function creates
1723 CFbsBitmap equivalent to the QPixmap, based on given mode and returns
1724 a CFbsBitmap object. The fromSymbianCFbsBitmap() function returns a
1725 QPixmap that is equivalent to the given bitmap and given mode.
1726
1727 \section1 Pixmap Transformations
1728
1729 QPixmap supports a number of functions for creating a new pixmap
1730 that is a transformed version of the original:
1731
1732 The scaled(), scaledToWidth() and scaledToHeight() functions
1733 return scaled copies of the pixmap, while the copy() function
1734 creates a QPixmap that is a plain copy of the original one.
1735
1736 The transformed() function returns a copy of the pixmap that is
1737 transformed with the given transformation matrix and
1738 transformation mode: Internally, the transformation matrix is
1739 adjusted to compensate for unwanted translation,
1740 i.e. transformed() returns the smallest pixmap containing all
1741 transformed points of the original pixmap. The static trueMatrix()
1742 function returns the actual matrix used for transforming the
1743 pixmap.
1744
1745 \sa QBitmap, QImage, QImageReader, QImageWriter
1746*/
1747
1748
1749/*!
1750 \typedef QPixmap::DataPtr
1751 \internal
1752*/
1753
1754/*!
1755 \fn DataPtr &QPixmap::data_ptr()
1756 \internal
1757*/
1758
1759/*!
1760 Returns true if this pixmap has an alpha channel, \e or has a
1761 mask, otherwise returns false.
1762
1763 \sa hasAlphaChannel(), mask()
1764*/
1765bool QPixmap::hasAlpha() const
1766{
1767 return data && (data->hasAlphaChannel() || !data->mask().isNull());
1768}
1769
1770/*!
1771 Returns true if the pixmap has a format that respects the alpha
1772 channel, otherwise returns false.
1773
1774 \sa hasAlpha()
1775*/
1776bool QPixmap::hasAlphaChannel() const
1777{
1778 return data && data->hasAlphaChannel();
1779}
1780
1781/*!
1782 \internal
1783*/
1784int QPixmap::metric(PaintDeviceMetric metric) const
1785{
1786 return data ? data->metric(metric) : 0;
1787}
1788
1789/*!
1790 \fn void QPixmap::setAlphaChannel(const QPixmap &alphaChannel)
1791 \obsolete
1792
1793 Sets the alpha channel of this pixmap to the given \a alphaChannel
1794 by converting the \a alphaChannel into 32 bit and using the
1795 intensity of the RGB pixel values.
1796
1797 The effect of this function is undefined when the pixmap is being
1798 painted on.
1799
1800 \warning This is potentially an expensive operation. Most usecases
1801 for this function are covered by QPainter and compositionModes
1802 which will normally execute faster.
1803
1804 \sa alphaChannel(), {QPixmap#Pixmap Transformations}{Pixmap
1805 Transformations}
1806 */
1807void QPixmap::setAlphaChannel(const QPixmap &alphaChannel)
1808{
1809 if (alphaChannel.isNull())
1810 return;
1811
1812 if (paintingActive()) {
1813 qWarning("QPixmap::setAlphaChannel: "
1814 "Cannot set alpha channel while pixmap is being painted on");
1815 return;
1816 }
1817
1818 if (width() != alphaChannel.width() && height() != alphaChannel.height()) {
1819 qWarning("QPixmap::setAlphaChannel: "
1820 "The pixmap and the alpha channel pixmap must have the same size");
1821 return;
1822 }
1823
1824 detach();
1825 data->setAlphaChannel(alphaChannel);
1826}
1827
1828/*!
1829 \obsolete
1830
1831 Returns the alpha channel of the pixmap as a new grayscale QPixmap in which
1832 each pixel's red, green, and blue values are given the alpha value of the
1833 original pixmap. The color depth of the returned pixmap is the system depth
1834 on X11 and 8-bit on Windows and Mac OS X.
1835
1836 You can use this function while debugging
1837 to get a visible image of the alpha channel. If the pixmap doesn't have an
1838 alpha channel, i.e., the alpha channel's value for all pixels equals
1839 0xff), a null pixmap is returned. You can check this with the \c isNull()
1840 function.
1841
1842 We show an example:
1843
1844 \snippet doc/src/snippets/alphachannel.cpp 0
1845
1846 \image alphachannelimage.png The pixmap and channelImage QPixmaps
1847
1848 \warning This is an expensive operation. The alpha channel of the
1849 pixmap is extracted dynamically from the pixeldata. Most usecases of this
1850 function are covered by QPainter and compositionModes which will normally
1851 execute faster.
1852
1853 \sa setAlphaChannel(), {QPixmap#Pixmap Information}{Pixmap
1854 Information}
1855*/
1856QPixmap QPixmap::alphaChannel() const
1857{
1858 return data ? data->alphaChannel() : QPixmap();
1859}
1860
1861/*!
1862 \internal
1863*/
1864QPaintEngine *QPixmap::paintEngine() const
1865{
1866 return data ? data->paintEngine() : 0;
1867}
1868
1869/*!
1870 \fn QBitmap QPixmap::mask() const
1871
1872 Extracts a bitmap mask from the pixmap's alpha channel.
1873
1874 \warning This is potentially an expensive operation. The mask of
1875 the pixmap is extracted dynamically from the pixeldata.
1876
1877 \sa setMask(), {QPixmap#Pixmap Information}{Pixmap Information}
1878*/
1879QBitmap QPixmap::mask() const
1880{
1881 return data ? data->mask() : QBitmap();
1882}
1883
1884/*!
1885 Returns the default pixmap depth used by the application.
1886
1887 On Windows and Mac, the default depth is always 32. On X11 and
1888 embedded, the depth of the screen will be returned by this
1889 function.
1890
1891 \sa depth(), QColormap::depth(), {QPixmap#Pixmap Information}{Pixmap Information}
1892
1893*/
1894int QPixmap::defaultDepth()
1895{
1896#if defined(Q_WS_QWS)
1897 return QScreen::instance()->depth();
1898#elif defined(Q_WS_X11)
1899 return QX11Info::appDepth();
1900#elif defined(Q_WS_WINCE)
1901 return QColormap::instance().depth();
1902#elif defined(Q_WS_WIN)
1903 return 32; // XXX
1904#elif defined(Q_WS_PM)
1905 return 32; // @todo check this
1906#elif defined(Q_WS_MAC)
1907 return 32;
1908#elif defined(Q_OS_SYMBIAN)
1909 return S60->screenDepth;
1910#endif
1911}
1912
1913/*!
1914 Detaches the pixmap from shared pixmap data.
1915
1916 A pixmap is automatically detached by Qt whenever its contents are
1917 about to change. This is done in almost all QPixmap member
1918 functions that modify the pixmap (fill(), fromImage(),
1919 load(), etc.), and in QPainter::begin() on a pixmap.
1920
1921 There are two exceptions in which detach() must be called
1922 explicitly, that is when calling the handle() or the
1923 x11PictureHandle() function (only available on X11). Otherwise,
1924 any modifications done using system calls, will be performed on
1925 the shared data.
1926
1927 The detach() function returns immediately if there is just a
1928 single reference or if the pixmap has not been initialized yet.
1929*/
1930void QPixmap::detach()
1931{
1932 if (!data)
1933 return;
1934
1935 QPixmapData::ClassId id = data->classId();
1936 if (id == QPixmapData::RasterClass) {
1937 QRasterPixmapData *rasterData = static_cast<QRasterPixmapData*>(data.data());
1938 rasterData->image.detach();
1939 }
1940
1941 if (data->is_cached && data->ref == 1)
1942 QImagePixmapCleanupHooks::executePixmapDataModificationHooks(data.data());
1943
1944#if defined(Q_WS_MAC)
1945 QMacPixmapData *macData = id == QPixmapData::MacClass ? static_cast<QMacPixmapData*>(data.data()) : 0;
1946 if (macData) {
1947 if (macData->cg_mask) {
1948 CGImageRelease(macData->cg_mask);
1949 macData->cg_mask = 0;
1950 }
1951 }
1952#endif
1953
1954 if (data->ref != 1) {
1955 *this = copy();
1956 }
1957 ++data->detach_no;
1958
1959#if defined(Q_WS_X11)
1960 if (data->classId() == QPixmapData::X11Class) {
1961 QX11PixmapData *d = static_cast<QX11PixmapData*>(data.data());
1962 d->flags &= ~QX11PixmapData::Uninitialized;
1963
1964 // reset the cache data
1965 if (d->hd2) {
1966 XFreePixmap(X11->display, d->hd2);
1967 d->hd2 = 0;
1968 }
1969 }
1970#elif defined(Q_WS_MAC)
1971 if (macData) {
1972 macData->macReleaseCGImageRef();
1973 macData->uninit = false;
1974 }
1975#endif
1976}
1977
1978/*!
1979 \fn QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1980
1981 Converts the given \a image to a pixmap using the specified \a
1982 flags to control the conversion. The \a flags argument is a
1983 bitwise-OR of the \l{Qt::ImageConversionFlags}. Passing 0 for \a
1984 flags sets all the default options.
1985
1986 In case of monochrome and 8-bit images, the image is first
1987 converted to a 32-bit pixmap and then filled with the colors in
1988 the color table. If this is too expensive an operation, you can
1989 use QBitmap::fromImage() instead.
1990
1991 \sa toImage(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
1992*/
1993QPixmap QPixmap::fromImage(const QImage &image, Qt::ImageConversionFlags flags)
1994{
1995 if (image.isNull())
1996 return QPixmap();
1997
1998 QGraphicsSystem* gs = QApplicationPrivate::graphicsSystem();
1999 QScopedPointer<QPixmapData> data(gs ? gs->createPixmapData(QPixmapData::PixmapType)
2000 : QGraphicsSystem::createDefaultPixmapData(QPixmapData::PixmapType));
2001 data->fromImage(image, flags);
2002 return QPixmap(data.take());
2003}
2004
2005/*!
2006 \fn QPixmap QPixmap::grabWindow(WId window, int x, int y, int
2007 width, int height)
2008
2009 Creates and returns a pixmap constructed by grabbing the contents
2010 of the given \a window restricted by QRect(\a x, \a y, \a width,
2011 \a height).
2012
2013 The arguments (\a{x}, \a{y}) specify the offset in the window,
2014 whereas (\a{width}, \a{height}) specify the area to be copied. If
2015 \a width is negative, the function copies everything to the right
2016 border of the window. If \a height is negative, the function
2017 copies everything to the bottom of the window.
2018
2019 The window system identifier (\c WId) can be retrieved using the
2020 QWidget::winId() function. The rationale for using a window
2021 identifier and not a QWidget, is to enable grabbing of windows
2022 that are not part of the application, window system frames, and so
2023 on.
2024
2025 The grabWindow() function grabs pixels from the screen, not from
2026 the window, i.e. if there is another window partially or entirely
2027 over the one you grab, you get pixels from the overlying window,
2028 too. The mouse cursor is generally not grabbed.
2029
2030 Note on X11that if the given \a window doesn't have the same depth
2031 as the root window, and another window partially or entirely
2032 obscures the one you grab, you will \e not get pixels from the
2033 overlying window. The contents of the obscured areas in the
2034 pixmap will be undefined and uninitialized.
2035
2036 \warning In general, grabbing an area outside the screen is not
2037 safe. This depends on the underlying window system.
2038
2039 \sa grabWidget(), {Screenshot Example}
2040*/
2041
2042/*!
2043 \internal
2044*/
2045QPixmapData* QPixmap::pixmapData() const
2046{
2047 return data.data();
2048}
2049
2050/*!
2051 \enum QPixmap::HBitmapFormat
2052
2053 \bold{Win32 only:} This enum defines how the conversion between \c
2054 HBITMAP and QPixmap is performed.
2055
2056 \warning This enum is only available on Windows.
2057
2058 \value NoAlpha The alpha channel is ignored and always treated as
2059 being set to fully opaque. This is preferred if the \c HBITMAP is
2060 used with standard GDI calls, such as \c BitBlt().
2061
2062 \value PremultipliedAlpha The \c HBITMAP is treated as having an
2063 alpha channel and premultiplied colors. This is preferred if the
2064 \c HBITMAP is accessed through the \c AlphaBlend() GDI function.
2065
2066 \value Alpha The \c HBITMAP is treated as having a plain alpha
2067 channel. This is the preferred format if the \c HBITMAP is going
2068 to be used as an application icon or systray icon.
2069
2070 \sa fromWinHBITMAP(), toWinHBITMAP()
2071*/
2072
2073/*! \fn HBITMAP QPixmap::toWinHBITMAP(HBitmapFormat format) const
2074 \bold{Win32 only:} Creates a \c HBITMAP equivalent to the QPixmap,
2075 based on the given \a format. Returns the \c HBITMAP handle.
2076
2077 It is the caller's responsibility to free the \c HBITMAP data
2078 after use.
2079
2080 \warning This function is only available on Windows.
2081
2082 \sa fromWinHBITMAP(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2083*/
2084
2085/*! \fn QPixmap QPixmap::fromWinHBITMAP(HBITMAP bitmap, HBitmapFormat format)
2086 \bold{Win32 only:} Returns a QPixmap that is equivalent to the
2087 given \a bitmap. The conversion is based on the specified \a
2088 format.
2089
2090 \warning This function is only available on Windows.
2091
2092 \sa toWinHBITMAP(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2093
2094*/
2095
2096/*! \fn HICON QPixmap::toWinHICON() const
2097 \since 4.6
2098
2099 \bold{Win32 only:} Creates a \c HICON equivalent to the QPixmap.
2100 Returns the \c HICON handle.
2101
2102 It is the caller's responsibility to free the \c HICON data after use.
2103
2104 \warning This function is only available on Windows.
2105
2106 \sa fromWinHICON(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2107*/
2108
2109/*! \fn QPixmap QPixmap::fromWinHICON(HICON icon)
2110 \since 4.6
2111
2112 \bold{Win32 only:} Returns a QPixmap that is equivalent to the given
2113 \a icon.
2114
2115 \warning This function is only available on Windows.
2116
2117 \sa toWinHICON(), {QPixmap#Pixmap Conversion}{Pixmap Conversion}
2118
2119*/
2120
2121/*! \fn const QX11Info &QPixmap::x11Info() const
2122 \bold{X11 only:} Returns information about the configuration of
2123 the X display used by the screen to which the pixmap currently belongs.
2124
2125 \warning This function is only available on X11.
2126
2127 \sa {QPixmap#Pixmap Information}{Pixmap Information}
2128*/
2129
2130/*! \fn Qt::HANDLE QPixmap::x11PictureHandle() const
2131 \bold{X11 only:} Returns the X11 Picture handle of the pixmap for
2132 XRender support.
2133
2134 This function will return 0 if XRender support is not compiled
2135 into Qt, if the XRender extension is not supported on the X11
2136 display, or if the handle could not be created. Use of this
2137 function is not portable.
2138
2139 \warning This function is only available on X11.
2140
2141 \sa {QPixmap#Pixmap Information}{Pixmap Information}
2142*/
2143
2144/*! \fn int QPixmap::x11SetDefaultScreen(int screen)
2145 \internal
2146*/
2147
2148/*! \fn void QPixmap::x11SetScreen(int screen)
2149 \internal
2150*/
2151
2152/*! \fn QRgb* QPixmap::clut() const
2153 \internal
2154*/
2155
2156/*! \fn int QPixmap::numCols() const
2157 \obsolete
2158 \internal
2159 \sa colorCount()
2160*/
2161
2162/*! \fn int QPixmap::colorCount() const
2163 \since 4.6
2164 \internal
2165*/
2166
2167/*! \fn const uchar* QPixmap::qwsBits() const
2168 \internal
2169 \since 4.1
2170*/
2171
2172/*! \fn int QPixmap::qwsBytesPerLine() const
2173 \internal
2174 \since 4.1
2175*/
2176
2177QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.