How to make QGraphicsItem display background in QGraphicsScene?

In QGraphicsScene , I have a background set with several QGraphicsItem on top of it. These graphic elements have an arbitrary shape. I would like to make another QGraphicsItem, i.e. A circle that, when placed over these elements, will essentially show the background in that circle, rather than being filled with color.

It would look like you have a background with several layers on top of it in Photoshop. Then, use the circular selection tool to remove all layers on top of the background to show the background in the circle.

Or another way to view it may be to have a set of opacity, but this opacity affects the elements directly below it (but only inside the ellipse) to show the background.

+7
source share
1 answer

The following steps may work. It basically extends the normal QGraphicsScene with the ability to only display its background for any QPainter . Then, your cut-out graphic element simply displays the background of the scene on top of other elements. For this to work, the cut element must have the highest Z value.

screen shot

 #include <QtGui> class BackgroundDrawingScene : public QGraphicsScene { public: explicit BackgroundDrawingScene() : QGraphicsScene() {} void renderBackground(QPainter *painter, const QRectF &source, const QRectF &target) { painter->save(); painter->setWorldTransform( QTransform::fromTranslate(target.left() - source.left(), target.top() - source.top()), true); QGraphicsScene::drawBackground(painter, source); painter->restore(); } }; class CutOutGraphicsItem : public QGraphicsEllipseItem { public: explicit CutOutGraphicsItem(const QRectF &rect) : QGraphicsEllipseItem(rect) { setFlag(QGraphicsItem::ItemIsMovable); } protected: void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { BackgroundDrawingScene *bgscene = dynamic_cast<BackgroundDrawingScene*>(scene()); if (!bgscene) { return; } painter->setClipPath(shape()); bgscene->renderBackground(painter, mapToScene(boundingRect()).boundingRect(), boundingRect()); } }; int main(int argc, char **argv) { QApplication app(argc, argv); BackgroundDrawingScene scene; QRadialGradient gradient(0, 0, 10); gradient.setSpread(QGradient::RepeatSpread); scene.setBackgroundBrush(gradient); scene.addRect(10., 10., 100., 50., QPen(Qt::SolidLine), QBrush(Qt::red)); scene.addItem(new CutOutGraphicsItem(QRectF(20., 20., 20., 20.))); QGraphicsView view(&scene); view.show(); return app.exec(); } 
+7
source

All Articles