【问题标题】:Hide area of QGraphicsItem that is out of boundary隐藏超出边界的 QGraphicsItem 区域
【发布时间】:2018-11-03 00:35:25
【问题描述】:

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

例如。

篮球的左边部分被隐藏了。

【问题讨论】:

  • 你可以更好地解释自己,我不明白你的意思
  • 我添加了更多信息。哪一部分不清楚?
  • 您希望它仅在它位于某个区域(例如矩形)内时显示,并且如果它位于该部分之外,则该部分被剪切。我是对的?
  • 是的,没错。

标签: c++ qt qt5 qgraphicsscene qgraphicsitem


【解决方案1】:

你必须使用setClipPath()

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

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

QPainterPath 是一个矩形,其左上角是 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();
}

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

【讨论】:

  • 我想知道 OP 的 certain boundary 是什么意思。为什么不直接在篮球上使用一个包含透明堆栈的层...
  • 我已编辑问题以澄清certain boundary。目前没有固定的方法。
  • @ALH 一个 QGraphicSscene 是 QGraphicsView 中的每个人,没有限制,解释你如何确定那个区域,不要混淆 sceneRect() 和 QGraphicsScene。在我的示例中,我添加了一个项目,以便该区域可见,但您可以删除 path_item,在我的示例中,它由 QPainterPath 确定。
  • @ALH 我已经为我的答案添加了更清晰的解释,请查看它。
  • 嗯,使用您的代码,看起来图像在灰色背景上仍然可见。
猜你喜欢
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-06
  • 2021-12-29
  • 1970-01-01
  • 2018-09-15
相关资源
最近更新 更多