How to partially draw a QGraphicsPixmapItem
-
Hi,
I am making a widget for comparing 2 images. LUMINAR for example has what I want to do. One image on the left, another one on the right and a slider to define how much of the left and right images to show
Is it possible to partially draw a pixmap set to a QGraphicsPixmapItem or set a transparency mask?
All I found so far would be to store the QPixmap call QPixmap::copy, set a new pixmap to each QGraphicsPixmapItem and set the position of both images.
It doesn't sound like an efficient way of do this.
-
@Asperamanca said in How to partially draw a QGraphicsPixmapItem:
case I would not use the QGraphicsPixmapItem (not much code in it, anyway), but rather create a custom QGraphicsItem that simply paints only the portion of the p
Thanks @Asperamanca. I went that route and it was very straight forward. Performance is acceptable too.
imageitem.h
#pragma once #include <QGraphicsItem> class ImageItem : public QGraphicsItem { public: ImageItem(QGraphicsItem* parent = Q_NULLPTR); ~ImageItem(); public: void setImage(const QImage& pixmap); QRect imageRect() const; QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR); void setSubRegion(const QRectF& rect); protected: QImage m_image; QRectF m_boundingRect; QRectF m_target; QRectF m_souce; };
imageitem.cpp
#include "imageitem.h" #include <QPainter> ImageItem::ImageItem(QGraphicsItem* parent /*= Q_NULLPTR*/) : QGraphicsItem(parent) { } ImageItem::~ImageItem() { } void ImageItem::setImage(const QImage & image) { m_image = image; m_boundingRect = m_image.rect(); } QRect ImageItem::imageRect() const { return m_image.rect(); } QRectF ImageItem::boundingRect() const { return m_boundingRect; } void ImageItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { Q_UNUSED(option); Q_UNUSED(widget); painter->drawImage(m_target, m_image, m_souce); } bool ImageItem::setSubRegion(const QRect & rect) { QRect imageRect = m_image.rect(); if (imageRect.contains(rect)) { m_souce = rect; m_target = QRect(0, 0, rect.width(), rect.height()); m_boundingRect = m_target; update(); return true; } else { return false; } }