Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a multi-colored line in Qt

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?

like image 391
Pietro Lorefice Avatar asked Dec 16 '22 04:12

Pietro Lorefice


1 Answers

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:

Fat inverted line over funky colors

Experiment with the other composition modes to get more interesting effects.

like image 143
Mat Avatar answered Jan 10 '23 11:01

Mat