以下可能有效。它基本上擴展了一個正常的QGraphicsScene
,只能渲染它的背景到任何QPainter
。然後,您的「剪切」圖形項目只會將場景背景渲染到其他項目的頂部。爲此,切出的項目必須具有最高的Z值。
#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();
}
的程序,我用所謂的實時繪製所謂的「推背」對象概括這一點。相當有用,你可以考慮使用類似的泛化:http://www.mediachance.com/realdraw/help/index.html?pushback.htm – HostileFork