2009-07-23 57 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]); 
     } 
    } 
}