Qt 实现可移动的QGraphicsObject子类
我试图制作一个QGraphicObject,它代表一个圆角矩形,可以用鼠标移动 项目似乎绘制正确,在文档中搜索后,我发现我必须设置标志Qt 实现可移动的QGraphicsObject子类,qt,draggable,qgraphicsitem,Qt,Draggable,Qgraphicsitem,我试图制作一个QGraphicObject,它代表一个圆角矩形,可以用鼠标移动 项目似乎绘制正确,在文档中搜索后,我发现我必须设置标志QGraphicsItem::ItemIsMovable,这使项目朝着正确的方向移动,但它总是比鼠标移动得更快,那么我做错了什么 以下是.h文件: class GraphicRoundedRectObject : public GraphicObject { Q_OBJECT public: explicit GraphicRoundedRectO
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);
}
#包括“GraphicRoundedStructObject.h”
#包括
GraphicRoundedStrotObject::GraphicRoundedStrotObject(
qrealx,
克利里,
宽度,
实际高度,
桡骨,
QGraphicsItem*父级
)
:GraphicObject(父对象)
,m_半径(半径)
,m_宽度(宽度)
,m_高度(高度)
{
setX(x);
赛蒂(y);
setFlag(QGraphicsItem::ItemIsMovable);
}
GraphicRoundedStructObject::~GraphicRoundedStructObject(){
}
void Graphics RoundedStructObject::paint
(QPainter*油漆工、const QStyleOptionGraphicsItem*、QWidget*){
画师->drawRoundedRect(x(),y(),m_宽度,m_高度,m_半径,m_半径);
}
QRectF GraphicRoundedStructObject::boundingRect()常量{
返回QRectF(x(),y(),m_宽度,m_高度);
}
这是因为您在父坐标而不是对象坐标中绘制矩形
应该是:
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);
}