1

我正在尝试制作一个 QGraphicObject ,它代表一个可以使用鼠标移动的圆角矩形。

该项目似乎绘制正确,在文档中搜索后,我发现我必须设置QGraphicsItem::ItemIsMovable 使项目朝正确方向移动的标志,但它总是比鼠标移动得快,所以我做错了什么?

这是.h文件:

class GraphicRoundedRectObject : public GraphicObject
{
    Q_OBJECT
public:
    explicit GraphicRoundedRectObject(
            qreal x ,
            qreal y ,
            qreal width ,
            qreal height ,
            qreal radius=0,
            QGraphicsItem *parent = nullptr);
    virtual ~GraphicRoundedRectObject();


    qreal radius() const;
    void setRadius(qreal radius);
    qreal height() const ;
    void setHeight(qreal height) ;
    qreal width() const ;
    void setWidth(qreal width) ;

    void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override;
    QRectF boundingRect() const override;

private:
    qreal m_radius;
    qreal m_width;
    qreal m_height;
};

和 .cpp :

#include "graphicroundedrectobject.h"
#include <QPainter>

GraphicRoundedRectObject::GraphicRoundedRectObject(
        qreal x ,
        qreal y ,
        qreal width ,
        qreal height ,
        qreal radius,
        QGraphicsItem *parent
        )
    : GraphicObject(parent)
    , m_radius(radius)
    , m_width(width)
    , m_height(height)
{
    setX(x);
    setY(y);
    setFlag(QGraphicsItem::ItemIsMovable);
}

GraphicRoundedRectObject::~GraphicRoundedRectObject() {
}

void GraphicRoundedRectObject::paint
(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget*) {
    painter->drawRoundedRect(x(), y(),m_width, m_height, m_radius, m_radius );
}

QRectF GraphicRoundedRectObject::boundingRect() const {
    return QRectF(x(), y(), m_width, m_height);
}
4

1 回答 1

2

这是因为您在父坐标而不是对象的坐标中绘制矩形。

它应该是:

void GraphicRoundedRectObject::paint(QPainter *painter,
                                     const QStyleOptionGraphicsItem *, QWidget*) {
    painter->drawRoundedRect(0.0, 0.0,m_width, m_height, m_radius, m_radius );
}

QRectF GraphicRoundedRectObject::boundingRect() const {
    return QRectF(0.0, 0.0, m_width, m_height);
}
于 2013-02-25T08:05:42.477 回答