Reputation: 4918
I'm trying to build an interface using custom widgets, and have run into the following problem.
I have a widget Rectangle
which I want to use as an interactive element in my interface. To define a rectangle I just need to give it a parent, so it knows what window to draw itself in, and a position [x,y, width, height]
defining its position and size. (I know that some of you will say "You should be using layouts as opposed to absolute positioning" but I am 100% sure that I need absolute positioning for this particular application).
from PySide.QtCore import *
from PySide.QtGui import *
import sys
class Rectangle(QWidget):
def __init__(self, parent, *args):
super(self.__class__,self).__init__(parent)
print parent, args
#expect args[0] is a list in the form [x,y,width,height]
self.setGeometry(*args[0])
def enterEvent(self, e):
print 'Enter'
def leaveEvent(self, e):
print 'Leave'
def paintEvent(self, e):
print 'Painted: ',self.pos
painter = QPainter(self)
painter.setPen(Qt.NoPen)
painter.setBrush(QColor(200,100,100))
painter.drawRect(0,0,self.width()-1, self.height()-1)
painter.end()
I also have a Window
widget which is the canvas on which my visualization is to be drawn. In the Window
's __init__()
definition I create a rectangle A at 20,40.
class Window(QWidget):
def __init__(self):
super(self.__class__, self).__init__()
self.widgets = [Rectangle(self,[20,40,100,80])]
self.setMouseTracking(True)
self.setGeometry(300,300,800,600)
self.setWindowTitle('Window')
self.show()
def addWidget(self,Widget, *args):
self.widgets += [Widget(self, *args)]
self.update()
def mousePressEvent(self, e):
for widget in self.widgets:
print widget.geometry()
Since I am building a visualization, I want to create my Window
and then add widgets to it afterwords, so I create an instance mWindow
, which should already have rectangle A defined. I then use my window's addWidget()
method to add a second rectangle at 200,200 - call it rectangle B.
if __name__ == "__main__":
app= QApplication(sys.argv)
mWindow = Window()
mWindow.addWidget(Rectangle, [200,200,200,80])
sys.exit(app.exec_())
The issue I have is that only rectangle A actually gets drawn.
I know that both rectangle A and **rectangle B are getting instantiated and both have myWindow
as their parent widgets, because of the output of print parent
in the constructor for Rectangle
.
However, when I resize the window to force it to repaint itself, the paintEvent()
method is only called on rectangle A, not rectangle B. What am I missing?
Upvotes: 2
Views: 1192
Reputation: 7930
You just forgot to show the rectangle. In addWidget
, add this before self.update()
:
self.widgets[-1].show()
The reason why you don't need show
for the first rectangle object is because it is
created in the Window constructor. Then, Qt itself is making sure objects are properly
shown (which is misleading, I agree...).
Upvotes: 3