c++ - 隐藏 QGraphicsItem 超出边界的区域

标签 c++ qt qt5 qgraphicsscene qgraphicsitem

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

例如。 enter image description here

篮球的左侧部分被隐藏。

最佳答案

您必须使用setClipPath()

在下面的代码中,我创建了一个继承自QGraphicsPixmapItem的类(对于继承自QGraphicsItem的其他类也可以这样做),并且我创建了方法setBoundaryPath() 接收指示可见区域的 QPainterPath,例如在代码中使用:

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

QPainterPath 是一个矩形,其左上角是 QGraphicsScene 的点 (100, 100),宽度为 400200高度。

#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 中找到示例代码.

关于c++ - 隐藏 QGraphicsItem 超出边界的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50498219/

相关文章:

c++ - 添加自定义小部件作为 QTableWidget Horizo​​ntalHeader

c++ - 总是重复随机选择

c++ - 运算符 < 和 > 如何与指针一起使用?

c# - 在将线条渲染到屏幕外缓冲区上时,Direct 2D 是否会比 Qt 更好

c++ - wglGetCurrentDC 未解析的外部

python - PyQt4中QWebView的多线程

c++ - 更改 Qt 中的选项卡小部件设计

c++ - 当鼠标在 Qt 中窗口的自定义小部件上时如何移动整个窗口?

c++ - 循环菜单重复自己

c++ - 在 boost::char_separator 中使用空格作为分隔符