What I'm trying to achieve is the following: I have a QGraphicsScene
with a QGraphicsPixmapItem
shown in it. The pixmap has multiple colors and I need to draw a line across the pixmap that must be visible and recognizable in every single point.
My idea is to draw a line where every pixel has the negative (complementary) color of the pixmap's relative pixel. So I thought about subclassing QGraphicsItem
and reimplement the paint()
method to draw a multi-colored line.
However I'm stuck because I don't know how I can retrieve the pixel information of the pixmap from the paint
function, and even if I found out, I can't think of a way to draw the line in this way.
Could you give me some advice on how to proceed?
You can use QPainter
's compositionMode
property to do something like this pretty easily, without having to read the source pixel colors.
Simple sample QWidget
with a custom paintEvent
implementation, which you should be able to adapt to your item's paint
method:
#include <QtGui>
class W: public QWidget {
Q_OBJECT
public:
W(QWidget *parent = 0): QWidget(parent) {};
protected:
void paintEvent(QPaintEvent *) {
QPainter p(this);
// Draw boring background
p.setPen(Qt::NoPen);
p.setBrush(QColor(0,255,0));
p.drawRect(0, 0, 30, 90);
p.setBrush(QColor(255,0,0));
p.drawRect(30, 0, 30, 90);
p.setBrush(QColor(0,0,255));
p.drawRect(60, 0, 30, 90);
// This is the important part you'll want to play with
p.setCompositionMode(QPainter::RasterOp_SourceAndNotDestination);
QPen inverter(Qt::white);
inverter.setWidth(10);
p.setPen(inverter);
p.drawLine(0, 0, 90, 90);
}
};
This will output something like the following image:
Experiment with the other composition modes to get more interesting effects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With