PDA

View Full Version : why is z order not respected when items are parented [QGraphicsView]



amleto
30th August 2013, 23:15
I have made an example to demonstrate my problem - code is below (sorry, it's PyQt).

Consider this arrangement where the small rectangles are children of the larger one that surrounds them
9507

I have set the Z Value for all the small rects to 2.0. However, when you drag a small rect over a large rect that was instantiated after the small rect's parent, then the view/scene will render the small rect under the large one! This is annoying me since I always want small rects to be on top.

Does anyone know a work around?

I 'need' the parenting because the larger rects are also movable and I want the contained small rect to move with it. I don't think I should have resort to managing move events myself for this.




import sys
from PyQt4 import QtGui, QtCore

if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)

view = QtGui.QGraphicsView()
view.setScene(QtGui.QGraphicsScene(view))

r1 = view.scene().addRect(50,50,50,50)
r2 = view.scene().addRect(120,50,50,50)
r3 = view.scene().addRect(190,50,50,50)

r1.setBrush(QtGui.QColor(50,20,20))
r2.setBrush(QtGui.QColor(50,20,20))
r3.setBrush(QtGui.QColor(50,30,20))

r1.setFlags(QtGui.QGraphicsItem.ItemIsMovable)
r2.setFlags(QtGui.QGraphicsItem.ItemIsMovable)
r3.setFlags(QtGui.QGraphicsItem.ItemIsMovable)

rr1 = view.scene().addRect(50,50,10,10)
rr2 = view.scene().addRect(120,50,10,10)
rr3 = view.scene().addRect(190,50,10,10)

rr1.setBrush(QtGui.QColor(250,200,200))
rr2.setBrush(QtGui.QColor(200,250,200))
rr3.setBrush(QtGui.QColor(200,200,250))

rr1.setFlags(QtGui.QGraphicsItem.ItemIsMovable | QtGui.QGraphicsItem.ItemIsSelectable)
rr2.setFlags(QtGui.QGraphicsItem.ItemIsMovable | QtGui.QGraphicsItem.ItemIsSelectable)
rr3.setFlags(QtGui.QGraphicsItem.ItemIsMovable | QtGui.QGraphicsItem.ItemIsSelectable)
rr1.setZValue(2.0)
rr2.setZValue(2.0)
rr3.setZValue(2.0)

rr1.setParentItem(r1)
rr2.setParentItem(r2)
rr3.setParentItem(r3)

view.show()

sys.exit(app.exec_())

Santosh Reddy
31st August 2013, 11:31
As items are painted by the view, starting with the parent items and then drawing children, in ascending stacking order. The child item will inherit the stacking order of the parent (or it's parent's parent). In other words setting z order on any item is not effective if it has parent item.

I don't think there is any other way other than implementing move event, by temporaryly elivating the z order of the item's parent. BTW will QGraphicsItemGroup work fo you.

amleto
31st August 2013, 13:46
oh, item group looks handy. Let me try it out...