隐藏QGraphicsItem超出边界

时间:2018-05-23 22:11:42

标签: c++ qt qt5 qgraphicsscene qgraphicsitem

我在QGraphicsPixmap中有一个QGraphicsScene项。该项目的标记设置为ItemIsMovableItemIsSelectable。如何确保当项目移出某个边界时 - 它可以是QGraphicsScene,也可以只是固定坐标处的固定帧大小 - 该部分会被隐藏?

EG。 enter image description here

篮球的左侧部分变得隐藏起来。

1 个答案:

答案 0 :(得分:2)

您必须使用setClipPath()

在下面的代码中,我创建了一个继承自QGraphicsPixmapItem的类(与继承自QGraphicsItem的其他类相同),我创建了接收a的方法setBoundaryPath() QPainterPath表示可见区域,例如代码使用:

QPainterPath path;
path.addRect(QRectF(100, 100, 400, 200));

QPainterPath是一个矩形,其topleft是QGraphicsScene的(100, 100)点,宽度为400,高度为200

#include <QApplication>
#include <QGraphicsRectItem>
#include <QGraphicsView>

class GraphicsPixmapItem: public QGraphicsPixmapItem{

public:
    GraphicsPixmapItem(const QPixmap & pixmap,  QGraphicsItem *parent = 0):
        QGraphicsPixmapItem(pixmap, parent)
    {
        setFlag(QGraphicsItem::ItemIsMovable, true);
        setFlag(QGraphicsItem::ItemIsSelectable, true);
    }
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
        if(!m_boundaryPath.isEmpty()){
            QPainterPath path = mapFromScene(m_boundaryPath);
            if(!path.isEmpty())
                painter->setClipPath(path);
        }
        QGraphicsPixmapItem::paint(painter, option, widget);
    }

    QPainterPath boundaryPath() const{
        return m_boundaryPath;
    }
    void setBoundaryPath(const QPainterPath &boundaryPath){
        m_boundaryPath = boundaryPath;
        update();
    }

private:
    QPainterPath m_boundaryPath;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsView view;
    QGraphicsScene scene(0, 0, 600, 400);
    view.setScene(&scene);
    view.setBackgroundBrush(QBrush(Qt::gray));

    GraphicsPixmapItem *p_item = new GraphicsPixmapItem(QPixmap(":/ball.png"));
    p_item->setPos(100, 100);

    // Define the area that will be visible
    QPainterPath path;
    path.addRect(QRectF(100, 100, 400, 200));

    p_item->setBoundaryPath(path);
    scene.addItem(p_item);

    // the item is added to visualize the intersection
    QGraphicsPathItem *path_item = scene.addPath(path, QPen(Qt::black), QBrush(Qt::white));
    path_item->setZValue(-1);
    view.show();
    return a.exec();
}

enter image description here

enter image description here

您可以在此link中找到示例代码。