2009-07-23 60 views
3

任務:通過自動剪貼,在一張圖上繪製兩條不同顏色的線,並通過逐點添加點。C++和Qt - 二維圖形問題

那麼,我在做什麼。創建從QGraphicsView繼承的類GraphWidget。創建QGraphicsScene的成員。創建2個QPainterPath實例,並將它們添加到graphicsScene中。

然後,我最終調用graphWidget.Redraw(),其中調用兩個實例的QPainterPath.lineTo()。我期待這些圖形視圖的外觀,但它不會。

我厭倦了閱讀Qt的文檔和論壇。我究竟做錯了什麼?

+2

請張貼相關的片段,這將有助於我們理解你到目前爲止做了什麼。 – 2009-07-23 18:15:42

回答

4

我們需要知道更多,什麼不會發生?窗口是否出現?線條沒有繪製?同時嘗試這個示例代碼,如果你想:)編輯:更新顯示更新。

#include ... 

class QUpdatingPathItem : public QGraphicsPathItem { 
    void advance(int phase) { 
     if (phase == 0) 
      return; 
     int x = abs(rand()) % 100; 
     int y = abs(rand()) % 100; 
     QPainterPath p = path(); 
     p.lineTo(x, y); 
     setPath(p); 
    } 
}; 

int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 
    QGraphicsScene s; 
    QGraphicsView v(&s); 

    QUpdatingPathItem item; 
    item.setPen(QPen(QColor("red"))); 
    s.addItem(&item); 
    v.show(); 

    QTimer *timer = new QTimer(&s); 
    timer->connect(timer, SIGNAL(timeout()), &s, SLOT(advance())); 
    timer->start(1000); 

    return a.exec(); 
} 

你應該得到這樣的事情:

meh...

的路徑在任何QGraphicsPathItem當然可以稍後進行更新。你可能想保持原來的畫家路某處,以免造成所有路徑複製性能命中(我不知道如果QPainterPath是隱含共享...)

QPainterPath p = gPath.path(); 
p.lineTo(0, 42); 
gPath.setPath(p); 

動畫

看來,你正在嘗試做某種動畫/即時更新。在Qt中有這個完整的框架。在最簡單的形式中,您可以繼承QGraphicsPathItem的子類,重新實現其advance()插槽以自動從運動中獲取下一個點。剩下的唯一事情就是用所需的頻率調用s.advance()。

http://doc.trolltech.com/4.5/qgraphicsscene.html#advance

+0

出現窗口。 線條未畫出。如果我在調用scene.addPath()之前添加它們,它們就會出現,但是(如您的示例中)GraphicsView不會更新,如果我更改路徑(不會出現新行)。 – peterdemin 2009-07-23 19:16:43

1

Evan Teran,對此評論感到抱歉。

// Constructor: 
GraphWidget::GraphWidget(QWidget *parent) : 
     QGraphicsView(parent), 
     bounds(0, 0, 0, 0) 
{ 
    setScene(&scene); 
    QPen board_pen(QColor(255, 0, 0)); 
    QPen nature_pen(QColor(0, 0, 255)); 
    nature_path_item = scene.addPath(board_path, board_pen); 
    board_path_item = scene.addPath(nature_path, nature_pen); 
} 

// Eventually called func: 
void GraphWidget::Redraw() { 
    if(motion) { 
     double nature[6]; 
     double board[6]; 
     // Get coords: 
     motion->getNature(nature); 
     motion->getBoard(board); 
     if(nature_path.elementCount() == 0) { 
      nature_path.moveTo(nature[0], nature[1]); 
     } else { 
      nature_path.lineTo(nature[0], nature[1]); 
     } 
     if(board_path.elementCount() == 0) { 
      board_path.moveTo(board[0], board[1]); 
     } else { 
      board_path.lineTo(board[0], board[1]); 
     } 
    } 
}