QT:用 QGraphicsItem 自定义一个 箭头

匿名 (未验证) 提交于 2019-12-03 00:22:01

声明

class CLineItem : public QObject,public QGraphicsItem {     Q_OBJECT     Q_INTERFACES(QGraphicsItem) public:     explicit CLineItem(QObject *parent = 0);     ~CLineItem(void);      virtual QRectF boundingRect() const;     virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);      void setLineItem(QPointF startP, QPointF endP);     void setColor(QColor color);  private:     void CreatePointNodes(void);  private:     QPointF         m_EndP;     QPointF         m_points[3];     QColor          m_Color; };

定义:

CLineItem::CLineItem(QObject *parent) : QObject(parent) {     //setFlag(ItemIsMovable);     setFlag(ItemIsSelectable);     setAcceptHoverEvents(true);      m_Color = TypeLineColor; }  CLineItem::~CLineItem(void) {  }  QRectF CLineItem::boundingRect() const {     return QRectF(0, 0, m_EndP.x(), m_EndP.y()); }  void CLineItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {     painter->setRenderHint(QPainter::Antialiasing, true);                   //设置反走样,防锯齿     QPen pen(m_Color, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);     QBrush brush(m_Color, Qt::SolidPattern);      painter->setPen(pen);     painter->setBrush(brush);      QLineF line(0, 0, m_EndP.x(), m_EndP.y());     painter->drawLine(line);      painter->drawPolygon(m_points, 3);      /*pen.setWidth(1);     painter->setPen(pen);     brush.setColor(QColor(0,0,0,0));     painter->setBrush(brush);     painter->drawRect(boundingRect());*/ }  void CLineItem::setLineItem(QPointF startP, QPointF endP) {     m_EndP = endP - startP;      CreatePointNodes(); }  void CLineItem::setColor(QColor color) {     m_Color = color; }  void CLineItem::CreatePointNodes(void) {     float angle = atan2(m_EndP.y(), m_EndP.x()) + 3.1415926;//      m_points[0] = m_EndP;     m_points[1].setX(m_EndP.x() + ExtRefArrowLenght * cos(angle - ExtRefArrowDegrees));//求得箭头点1坐标     m_points[1].setY(m_EndP.y() + ExtRefArrowLenght * sin(angle - ExtRefArrowDegrees));     m_points[2].setX(m_EndP.x() + ExtRefArrowLenght * cos(angle + ExtRefArrowDegrees));//求得箭头点2坐标     m_points[2].setY(m_EndP.y() + ExtRefArrowLenght * sin(angle + ExtRefArrowDegrees)); }

使用:

CLineItem *LineItem = new CLineItem(this); LineItem->setLineItem(startP, endP); LineItem->setPos(startP); m_Scene->addItem(LineItem);

图中为用此自定义类创建的三个对象:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!