I am trying to have a python desktop application with metro (Windows 8) style, so a table of rectangles which can be clicked to do something.
I generate the table of rectangles (MyIcon) like this:
for sub_rectx in xrange(4):
for sub_recty in xrange(3):
tmp = MyIcon(sub_rectx*322, sub_recty*192, 300, 170, sub_recty+3*sub_rectx + 1, parent=parent)
and I have my class, which basically is a rectangle with an id:
class MyIcon(MyPanel):
def __init__(self, x, y, width, height, ide, parent=None):
super(MyPanel, self).__init__(parent)
QtGui.QGraphicsRectItem.__init__(self, x, y, width, height, parent)
self.ide = ide
def mousePressEvent(self, event):
self.setBrush(QtGui.QColor(255, 255, 255))
print self.ide
This code works fine the first time I click on a rectangle, printing the correct id, and changing the colour of the correct rectangle, however the next times I click on any rectangle it's always printing the id of the first rectangle I clicked and the colour is not changed (I assume because it's painting again the same rectangle as well).
Can anyone help me?
I see two issues:
1) when you call super(..) you have to pass the current class as first parameter (MyIcon
and not MyPanel
). Pass the proper parameters, and don't call the init function of QGraphicsRectItem there (your parent class probably does it).
2) In your mouse event handler, you should call the super function too:
super(MyIcon, self).mousePressEvent(event)
This should solve the issue.