The Objective
I am attempting to draw a rectangle in my window when a button is clicked.
The Problem
When I use the button to allow the rectangle to be drawn it draws the rectangle just behind the button: Rectangle behind button image
If I minimize and then reopen the window it draws the rectangle correctly so I assume it is a problem with focus but when I attempted to change the focus it didn't help.
Edit: Doing something with the original window when the button is clicked draws the rectangle in the right place. For example:
self.setStyleSheet("background-color: black; color: white")
This is a really messy solution though.
The Code
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
draw = False
def __init__(self):
super(Example, self).__init__()
self.initUI()
self.test = self
def initUI(self):
self.setGeometry(400, 400, 400, 400)
qbtn = QtGui.QPushButton('Paint', self)
qbtn.clicked.connect(self.buttn)
qbtn.resize(qbtn.sizeHint())
qbtn.move(50, 50)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Paint')
self.show()
def paintEvent(self, e):
qp = QtGui.QPainter()
qp.begin(self)
self.drawRectangles(qp)
qp.end()
def drawRectangles(self, qp):
if self.draw:
qp.setBrush(QtGui.QColor(000, 000, 255))
qp.drawRect(0, 0, 90, 60)
@QtCore.pyqtSlot()
def buttn(self):
self.draw = True
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()