自定义Item,点
// cgraphicsitem.h
#ifndef CGRAPHICSITEM_H
#define CGRAPHICSITEM_H
#include <QGraphicsItem>
#include <QGraphicsSceneMouseEvent>
class CGraphicsItem : public QGraphicsItem
{
public:
CGraphicsItem(QPointF p,QGraphicsItem* parent = 0);
QPointF getPoint(){
return m_point;}
void setPoint(QPointF p){
m_point = p;}
protected:
virtual QRectF boundingRect() const override;
virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *e);
private:
QPointF m_point;
};
#endif // CGRAPHICSITEM_H
// cgraphicsitem.cpp
#include "cgraphicsitem.h"
#include <QPen>
#include <QBrush>
#include <QPainter>
#include <QGraphicsScene>
#include <QCursor>
CGraphicsItem::CGraphicsItem(QPointF p,QGraphicsItem* parent)
: m_point(p)
, QGraphicsItem(parent)
{
setFlags(QGraphicsItem::ItemIsFocusable|
QGraphicsItem::ItemIsSelectable|
QGraphicsItem::ItemIsMovable);
this->setCursor(Qt::PointingHandCursor);
}
QRectF CGraphicsItem::boundingRect() const
{
return QRectF(-4,-4,8,8);
}
void CGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
QPen pen(Qt::yellow,2);
QBrush brush(Qt::blue);
this->setPos(m_point);
painter->setPen(pen);
painter->setBrush(brush);
painter->drawEllipse(-4,-4,8,8);
}
void CGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *e)
{
if(e->buttons() == Qt::LeftButton) {
qreal x = e->scenePos().x() - e->lastScenePos().x();
qreal y = e->scenePos().y() - e->lastScenePos().y();
this->parentItem()->moveBy(x,y);
}
return QGraphicsItem::mouseMoveEvent(e);
}
scene类负责响应view信号,实时画图
// cgraphicsscene.h
#ifndef CGRAPHICSSCENE_H
#define CGRAPHICSSCENE_H
#include <QGraphicsScene>
#include "cgraphicsitem.h"
#include <QPainterPath>
#include <QGraphicsPathItem>
class CGraphicsScene : public QGraphicsScene
{
Q_OBJECT
public:
enum Type {
T_None,
T_Point,
T_Line,
T_Circle,
T_Ellipse,
T_Rect,
T_RoundRect,
T_Polygon,
T_Bezier
};
enum State {
S_None,
S_Begin,
S_Moving,
S_Press,
S_End
};
CGraphicsScene(QObject *parent = 0);
private:
void BeginDraw(QPointF beginPos,QPointF nextPos,int type);
void MovingDraw(QPointF beginPos,QPointF movingPos,int type);
void PressDraw(QPointF beginPos,QPointF pressPos,int type);
void EndDraw(QPointF beginPos,QPointF endgPos,int type);
public slots:
void OnDrawImage(QPointF beginPos,QPointF nextPos,int type,int state);
private:
QList<QGraphicsPathItem*> m_itemList;
QGraphicsPathItem *m_currentItem;
QVector<QPointF> m_polygonVec;
QVector<QPointF> m_bezierVec;
};
#endif // CGRAPHICSSCENE_H
// cgraphicsscene.cpp
#include "cgraphicsscene.h"
#include <cmath>
#include <QPolygonF>