gpt4 book ai didi

qt - 如何让 QGraphicsItem 在 QGraphicsScene 中显示背景?

转载 作者:行者123 更新时间:2023-12-04 11:56:32 26 4
gpt4 key购买 nike

QGraphicsScene ,我背景设置了几个QGraphicsItem s 在它之上。这些图形项具有任意形状。我想制作另一个 QGraphicsItem,即一个圆圈,当放置在这些项目上时,它基本上会显示该圆圈内的背景,而不是填充颜色。

这有点像在 Photoshop 中具有多层背景。然后,使用圆形选框工具删除背景顶部的所有图层,以显示圆圈内的背景。

或者,另一种查看它的方法可能是设置不透明度,但此不透明度会影响其正下方的项目(但仅在椭圆内)以显示背景。

最佳答案

以下可能有效。它基本上扩展了一个正常的 QGraphicsScene能够仅将其背景渲染到任何 QPainter .然后,您的“切出”图形项目只是将场景背景渲染到其他项目之上。为此,剪下的项目必须具有最高的 Z 值。

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();
}

关于qt - 如何让 QGraphicsItem 在 QGraphicsScene 中显示背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11055214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com