2014-12-23 37 views
1

我試圖在QGraphicsView::drawBackground上正確顯示網格模式。似乎一切正常,直到我嘗試移動添加到場景的項目。QGraphicsView中的毛刺網格:: drawBackground

我添加一行在主窗口是這樣的:

GraphicsView的
QPen _Pen; 
    _Pen.setColor(Qt::red); 
    _Pen.setWidth(3); 

    QGraphicsLineItem* _Line=new QGraphicsLineItem(0,0,100,100); 
    _Line->setPen(_Pen); 
    _Line->setVisible(true); 
    _Line->setFlags(QGraphicsLineItem::ItemIsSelectable | QGraphicsLineItem::ItemIsMovable); 

    m_scene->addItem(_Line); 

方法:

GraphicsView::GraphicsView() : cellSize(20) 
{ 
    setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); 
} 

void GraphicsView::drawBackground(QPainter *p, const QRectF &crect) 
{ 
    p->save(); 
    p->setPen(QPen(Qt::black,1)); 

    for (int x = crect.topLeft().x(); x < crect.bottomRight().x(); x += cellSize) 
     for (int y = crect.topLeft().y(); y < crect.bottomRight().y(); y += cellSize) 
     p->drawPoint(x, y); 

    p->restore(); 
} 

的問題可以在這裏看到:

Demonstration

當我移動該項目,它留下了一個網格點後面,這是不與原始網格對齊。

我不明白這個錯誤來自哪裏。我做錯了什麼?

回答

0

您在drawBackground中給出的區域並不總是完整的視圖。當場景中的某些東西發生變化時,只給予相關區域重繪。你從不同的「移動」區域的左上角開始。解決這個問題

一種方法是使的cellSize初始xy倍數:

for (int x = (int)crect.left()/cellSize*cellSize; x < crect.right(); x += cellSize) 
    for (int y = (int)crect.top()/cellSize*cellSize; y < crect.bottom(); y += cellSize) 
0

我能想到的2可能出現的問題:

1)更改視圖更新模式。選項描述爲here
這應該工作:

setViewportUpdateMode(SmartViewportUpdate); 

2)塗抹可由項是半個像素太小的項目邊界矩形引起。

(我意識到這個問題很舊,但也許會幫助別人)