2012-11-07 74 views
1

所有,我實現了一個QGraphicsItem這是一個多邊形。我通過使用QGraphicsEllipseItem作爲要點(用於拖拽功能)來加速開發。但是,我現在在update()功能中遇到困難。我的代碼發佈在最後,我的問題是:自定義QGraphicItem和重繪問題

  1. 我在這裏採取正確的做法嗎?我開始懷疑自己
  2. 我應該在我的執行過程中調用QGraphicsItem::update()嗎?我把它稱爲很多

其他一些信息:

  • 我做了一個骯髒的小黑客。在我的實際代碼中,我也從QObject繼承。這允許我在場景()上安裝eventFilter(我知道它已使用itemChange設置)。在場景中,我在鼠標移動過程中過濾QGraphicsSceneMouseEvent,並調用QGraphicsItem::update(),否則我的行不會重繪。
  • 當我現在從場景中刪除我的InteractivePolygon時,我的線條不會被刪除!我必須調用scene() - > update。我覺得事情不對。

聲明:

class InteractivePolygon : public QGraphicsItem 
{ 

public: 
    //Only important methods 
    QRectF boundingRect() const; 
    void paint(bla bla bla); 
    bool eventFilter(QObject *, QEvent *); 

private: 
    QList<QGraphicsEllipseItem *> m_points; 

    void AddPolygonPoint(QPointF); 
    QGraphicsEllipseItem * MakeNewPoint(QPointF); 
} 

實現:

QRectF InteractivePolygon::boundingRect() const 
{ 
    return childrenBoundingRect(); 
} 

void InteractivePolygon::paint(QPainter painter.. otherstuf) 
{ 
    QPen line_pen(QColor(255,0,0)); 
    painter->setPen(line_pen); 

    if(m_points.count() > 1) 
    { 
     for(int i = 1; i < m_points.count(); ++i) 
      painter->drawLine(m_points[i-1]->pos(), m_points[i]->pos()); 
    } 
} 

void AddPolygonPoint(QRectF point) 
{ 
    QGraphicsEllipseItem * new_item = MakeNewPoint(point); 
    new_item->setParent(this); 

    m_points->push_front(new_item); 

    update(); 
} 

QGraphicsEllipseItem * InteractivePolygon::MakeNewPoint(QPointF & new_point) 
{ 
    QGraphicsEllipseItem * result = 0; 
    result = new QGraphicsEllipseItem(); 
    result->setPos(new_point); 
    result->setRect(-4, -4, 8, 8); 
    result->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable) 

    return result; 
} 

//Lets pretend this method is correctly setup/exists 
bool InteractivePolygon::eventFilter(QObject *object, QEvent *event) 
{ 
    if(event->type() == QEvent::QEvent::GraphicsSceneMouseMove) 
    { 
     QGraphicsSceneMouseEvent * mouse_move = (QGraphicsSceneMouseEvent *)event; 
     //Selected index is set else, let's assume it works 
     if(selected_index) 
     { 
     update(); //If I don't do this, my lines in my paint() are not redrawn. 
     } 
    } 
} 

回答

0

的解決方案是prepareGeometryChange()每次我在我的項目發生了任何變化,將改變它的邊框。一切都正確重繪,並根據需要進行更新。

這使我可以刪除所有update()電話。