1. 程式人生 > >QT:用 QGraphicsItem 自定義一個 箭頭

QT:用 QGraphicsItem 自定義一個 箭頭

宣告

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);

圖中為用此自定義類建立的三個物件:
這裡寫圖片描述