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

标签 qt qgraphicsitem qgraphicsscene

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/

相关文章:

c++ - 拖动 View 时 QGraphicsItem 消失

graphics - 关于Qt Graphics View Framework在项目数量较多时的效率问题

python - 在QGraphicsItem上添加动画时遇到的一个问题

c++ - 如何获取在 QGraphicsView 中加载的图像像素位置 - 奇怪的 MapToScene() 行为

c++ - QGraphicsView fitInView 边距

c++ - qt setmodal 不起作用

qt - 使用 Qt 的 Cosmos DB

c++ - 我可以使用 Qt Creator 创建控制台应用程序吗?

Qt Creator 部署到 Windows 设置图标

c++ - 拖放 QGraphicSscene - 鼠标光标在小部件的中心