2011-07-04 55 views
0

我想實現應用程序,它允許用戶選擇幾個QGraphicsItems,然後將它們作爲一個組來旋轉。我知道我可以將所有項目添加到一個QGraphicsItemGroup,但我需要保留每個項目的Z-value。可能嗎?QGraphicsItem的 - 選擇和旋轉

我還有第二個問題。 我正在嘗試圍繞某個點旋轉QGraphicsItem(與(0,0)不同 - 比如說(200,150))。在那之後,我想再次旋轉這個項目,但是現在在(0,0)左右。我使用的代碼如下:

QPointF point(200,150); // point is (200,150) at first time and then it is changed to (0,0) - no matter how... 
    qreal x = temp.rx(); 
    qreal y = temp.ry(); 
    item->setTransform(item->transform()*(QTransform().translate(x,y).rotate(angle).translate(-x,-y))); 

我注意到,第二次旋轉後該項目不在身邊點(0,0)但周圍的一些其他點(我不知道是哪個)旋轉。我也注意到,如果我改變了操作順序,它一切都很好。

我在做什麼錯?

回答

0

關於你的第一個問題,爲什麼z值在把它們放到QGraphicsGroup中時會成爲問題? 另一方面,你也可以遍歷選定的項目,並應用轉換。

我想這個片段將解決你的第二個問題:

QGraphicsView view; 
QGraphicsScene scene; 

QPointF itemPosToRotate(-35,-35); 
QPointF pivotPoint(25,25); 

QGraphicsEllipseItem *pivotCircle = scene.addEllipse(-2.5,-2.5,5,5);    
pivotCircle->setPos(pivotPoint); 

QGraphicsRectItem *rect = scene.addRect(-5,-5,10,10); 
rect->setPos(itemPosToRotate); 

// draw some coordinate frame lines 
scene.addLine(-100,0,100,0); 
scene.addLine(0,100,0,-100); 

// do half-cicle rotation 
for(int j=0;j<=5;j++) 
for(int i=1;i<=20;i++) { 
    rect = scene.addRect(-5,-5,10,10); 
    rect->setPos(itemPosToRotate); 

    QPointF itemCenter = rect->pos(); 
    QPointF pivot = pivotCircle->pos() - itemCenter; 


    // your local rotation 
    rect->setRotation(45); 

    // your rotation around the pivot 
    rect->setTransform(QTransform().translate(pivot.x(), pivot.y()).rotate(180.0 * (qreal)i/20.0).translate(-pivot.x(),-pivot.y()),true); 
} 
view.setScene(&scene); 
view.setTransform(view.transform().scale(2,2)); 
view.show(); 

編輯: 如果你的意思是沿全局座標系原點改變旋轉旋轉:

rect->setTransform(QTransform().translate(-itemCenter.x(), -itemCenter.y()).rotate(360.0 * (qreal)j/5.0).translate(itemCenter.x(),itemCenter.y())); 
rect->setTransform(QTransform().translate(pivot.x(), pivot.y()).rotate(180.0 * (qreal)i/20.0).translate(-pivot.x(),-pivot.y()),true); 
+0

讓我們說我在我的場景(名稱= Z值) (item1 = 1,item2 = 2,item3 = 3,item4 = 4) item3 = 3)] = 5 此操作n將使item1和item3將會到達我的場景的頂部。無論物品是否分組,我都希望場景的「堆疊層」不變。 –

+0

我不明白你實際上想要做什麼... 要麼繪製一張圖片,要麼精確地改寫你的問題。 我發佈的代碼做了你想要的旋轉(你的第二個問題),除非「再一次,但是現在圍繞(0,0)」你的意思是關於全局座標系的原點。 在這種情況下,只需做類似於樞軸旋轉的另一個旋轉,但將樞軸更改爲(0,0)。 我仍然不知道你的意思是「堆棧層不變......」。 你想旋轉多個物體並保持其局部旋轉嗎? – pokey909