diegob
diegob

Reputation: 45

Color the area defined by Items intersection in Qt

I have some custom QGraphicsItems in a QGraphicsView of a QGraphicsScene. With items(QPoint(x, y)) method I retrieve all the items at given scene point.
Once these items are drawn they will not be moved, rotated or scaled, so their shapes will not change.

I would to know if there is a way to change the color of the overlapping area only (if I have at least two items, of course).

A different way to write my question is: given a starting point, color the scene until some borders are found.
I have not enough reputation to post an image, so I uploaded three examples of desired results here.

Edit 1: solution from Nejat works if I select a point that actually is within two Items' shapes, but it doesn't work if the point belongs to only one Item or to no Items (I uploaded an example of this case here).

Maybe should I use a different approach? Once painted, I don't need to change an item, so I will be interested also in a "flat/static" pixel-oriented solution. Could I use QImage class?

Edit 2: Nejat's answer was right for the original question. Btw, for my purpose I used a QImage, drawing on it all the shapes and finally using a "flood fill" algorithm to fill the area I wanted.

Upvotes: 2

Views: 1847

Answers (1)

Nejat
Nejat

Reputation: 32665

You can use the QGraphicsItem::shape () which returns a QPainterPath to retrieve the shape of an item. For taking the intersection path this can be used :

QPainterPath QPainterPath::intersected ( const QPainterPath & p ) const;

So you can get the intersection path of two items like:

QPainterPath intersectedPath = item1->shape()->intersected(item2->shape());

Now you can fill the intersected area by :

painter->setBrush(QColor(122, 163, 39));
painter->drawPath(intersectedPath);

Upvotes: 1

Related Questions