代码之家  ›  专栏  ›  技术社区  ›  Toloka

Qpainter绘制图像边界不透明

  •  0
  • Toloka  · 技术社区  · 2 年前

    我做了一个习惯 QGraphicsItem 我正在压倒 paint 用于绘制图像的函数 ghost.png ,一个具有复杂边界的角色,可以通过单击移动 降低 / 上面的 / 左边 / 正确的 图像的一侧。

    我知道这是因为 boundingRect ,我将其设置得更大,因为我需要绘制其他内容,例如:文本、健康栏等。。。

    我怎样才能保留更大的 boundingrect 并且还限制图像仅在点击图像时移动。

    我的班级:

    class DrawImage : public QGraphicsItem
    {
    public:
        DrawImage();
    
    protected:
        QRectF boundingRect() const override;
        void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
    };
    

    我的定义:

    DrawImage::DrawImage()
    {
        setFlag(ItemIsMovable);
    }
    
    QRectF DrawImage::boundingRect() const
    {
        return QRectF(0, 0, 100, 200);
    }
    
    void DrawImage::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
        auto ghost = QImage(":ghost.png");
        painter->drawImage(QRect(0, 0, 100, 100), ghost);
    }
    
    0 回复  |  直到 2 年前
        1
  •  2
  •   user17726418 Shajeen Ahamed    2 年前

    musicamante 说:

    覆盖[QGraphicsItem::] shape .

    以下是如何使 QGraphicsPixmapItem 仅当点击其时可移动 pixmap ,并拥有 boundingRect 围绕它:

    class DrawImage : public QGraphicsItem
    {
    public:
        DrawImage()
        {
            setFlag(ItemIsMovable);
        }
    
    protected:
        QRectF boundingRect() const override
        {
            return QRectF(0, 0, 100, 200);
        }
    
        void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
        {
            auto greenBall = QPixmap(":green.svg");
            QRect rect = boundingRect().toRect();
    
            //You can adjust where your pixmap is drawn
            //I chose the upper part of the bounding rect
            rect.adjust(0,0,0,-rect.height()/2);
            painter->drawPixmap(rect, greenBall);
    
            //I'm drawing the full bounding rect just to make it visible
            painter->setPen(Qt::green);
            painter->drawRect(boundingRect());
        }
    
        QPainterPath shape() const
        {
            //this is where you sepecify which area of your object allows the user to move it when clicked
            auto greenBall = QPixmap(":green.svg");
            QRect rect = boundingRect().toRect();
            
            //Make sure it is the same area where you're drawing your pixmap
            rect.adjust(0,0,0,-rect.height()/2);
            QPainterPath path;
            //add it as the shape you want, I chose an ellipse for the green circle
            path.addEllipse(rect);
            return path;
        }
    };
    

    结果如下:

    bounding rect around pixmap

    有关更多详细信息,请参阅源代码: