我试图制作一个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);
}
答案 0 :(得分: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);
}