Reputation: 2088
I'm new to Qt and Qt Graphics API.
I have a larger QPixMap
and a smaller QPixMap
. I need to replace a portion (a QRect
) of the larger one with the smaller one.
How am I supposed to achieve this?
Thanks.
UPDATE
QPainter::drawPixmap()
does not update the image represented by pImage->p_PixMap.
Code
class GraphicImage : public QObject,
public QGraphicsPixmapItem
{
Q_OBJECT
public:
GraphicImage(QPixmap* oImage,GraphiItemCtrl* pParent);
virtual ~GraphicImage(void);
QPixmap* p_PixMap;
};
- - - -
GraphicImage::GraphicImage(QPixmap* oImage,GraphiItemCtrl* pParent)
:QGraphicsPixmapItem(*oImage), p_Parent(pParent)
{
p_PixMap = oImage;
}
- - - -
void GraphiItemCtrl::SetImagePortion( QString sFileName, QRect rect, QPixmap pChildPixMap )
{
GraphicImage* pImage = map_CurrentImages[sFileName];
if ( !pImage )
return;
pChildPixMap.save("test.jpg");
QPixmap* pMap = pImage->p_PixMap;
QPainter pPainter(pMap);
pPainter.drawPixmap(rect, pChildPixMap);
qDebug() << rect.topLeft();
}
pChildPixMap.save("test.jpg");
saves the required portion of the image without an issue.
NOTE :
pImage
is inherited from QObject and QGraphicsPixmapItem.
pMap
is not NULL
Upvotes: 2
Views: 944
Reputation: 43662
Quick pseudocode:
QPainter painter(pixmap1);
painter.drawPixmap(QRect, pixmap2);
Take a look at the documentation here
Upvotes: 2
Reputation: 98545
You need to use a painter on the destination pixmap to draw the source pixmap in a given destination rectangle:
void draw(QPixmap &dst, const QRect &dstRect, const QPixmap &src) {
QPainter(dst).drawPixmap(dstRect, src);
}
If you're drawing multiple such pixmaps on one destination, you should hold on to the painter - it'd be wasteful to construct new painter over and over in a loop:
struct Replacement {
QRect dstRect;
QPixmap source;
};
void draw(QPixmap &dst, const QList<Replacement> &replacements) {
QPainter painter{dst};
for (auto & r : replacements)
painter.drawPixmap(r.dstRect, r.source);
}
Upvotes: 0
Reputation: 49329
The function you are looking for is:
void QPainter::drawPixmap(const QRect &rectangle, const QPixmap &pixmap)
It will draw the pixmap
into a rectangle
portion of the painter's target.
You may also want to use this one:
void QPainter::drawPixmap(const QRect &target, const QPixmap &pixmap, const QRect &source)
Which will draw a portion of the source into a portion of the target.
In both cases if the sizes mismatch the image will be scaled, so if you are getting poor results, you will additionally need to tweak the scaling method.
As established in this answer, setting setRenderHint(QPainter::SmoothPixmapTransform);
by itself does not seem to produce optimal results. If you want the best quality you will need to manually scale()
the pixmap and then draw it, which produces much better results than scaling it on the fly while painting.
Upvotes: 3