2011-10-11 30 views
6

我正在實施一個正在使用並顯示簡單圖形的應用程序。其中之一是一棵樹,就像一個自動機。使用OGDF和Qt顯示圖形

我決定除了Qt之外還使用OGDF,因爲我需要佈局。但我沒有得到這個......我必須自己實現所有繪圖/定位功能(比如從GraphAttributes獲取所有節點和邊緣座標)還是OGDF提供了一些很好的界面? (和GraphAttributes :: writeGML()一樣好)

回答

7

我找不到任何漂亮的界面,所以我只是自己提取座標,但是這種方法並不完美,因爲佈局算法返回的是負座標(相對於圖形中心點我認爲,而不是正常的源頭)。我的代碼看起來有點像這樣:

int nodeWidth = 30, nodeHeight = 30, siblingDistance = nodeWidth + nodeHeight; 

ogdf::TreeLayout treeLayout; 
treeLayout.siblingDistance(siblingDistance); 
treeLayout.call(GA); 

int width = GA.boundingBox().width(), height = GA.boundingBox().height(); 

ui->graphView->scene()->setSceneRect(QRect(0, 0, width+nodeWidth, height+nodeHeight)); 
cout << "Scene dimensions: " << GA.boundingBox().width() << " x " << GA.boundingBox().height() << endl; 

GA.setAllWidth(nodeWidth); 
GA.setAllHeight(nodeHeight); 

ogdf::edge e; 
forall_edges(e,graph){ 
    ogdf::node source = e->source(), target = e->target(); 
    int x1 = GA.x(source), y1 = GA.y(source); 
    int x2 = GA.x(target), y2 = GA.y(target); 
    QPainterPath p; 
    p.moveTo(x1 + nodeWidth/2, y1 + nodeHeight/2); 
    p.lineTo(x2 + nodeWidth/2, y2 + nodeHeight/2); 
    (void) ui->graphView->scene()->addPath(p, QPen(Qt::darkGray), QBrush(Qt::white)); 
} 

ogdf::node n; 
forall_nodes(n, graph) { 
    double x = GA.x(n); 
    double y = GA.y(n); 
    double w = GA.width(n); 
    double h = GA.height(n); 
    QRectF boundingRect(x, y, w, h); 
    cout << x << " : " << y << " : " << endl; 
    QRadialGradient radialGradient(boundingRect.center(), boundingRect.width()); 
    radialGradient.setColorAt(1.0, Qt::lightGray); 
    radialGradient.setColorAt(0.7, QColor(230,230,240)); 
    radialGradient.setColorAt(0.0, Qt::white); 
    (void) ui->graphView->scene()->addEllipse(boundingRect, QPen(Qt::black), QBrush(QRadialGradient(radialGradient))); 
    QGraphicsTextItem *text = ui->graphView->scene()->addText(QString(GA.labelNode(n).cstr())); 
    text->setPos(x, y); 
} 

// clear the graph after it has been displayed 
graph.clear(); 
+0

非常感謝!正如我現在看到的,我走在了正確的道路上。有示例代碼是非常有幫助的!你對OGDF有經驗嗎? – TeaOverflow

+0

哦,並且節點的負座標與QGraphicScene很好地工作,因爲它的'0,0'似乎也在它的中心。 – TeaOverflow