PDA

View Full Version : Unexpected Offset in paintEvent



shambalain61
24th February 2021, 09:11
Does anybody know, why the Rect drawn in the paintEvent does not cover the exact area of my QWidget but instead starts at an weird offset?



class ContainerWidget(QWidget):
def __init__(self):
super().__init__()
pal = QPalette()
pal.setColor(QPalette.Window, Qt.magenta)
self.setAutoFillBackground(True)
self.setPalette(pal)
def paintEvent(self, event):
opt = QStyleOption()
opt.initFrom(self)
painter = QPainter(self)
painter.setBrush( Qt.red )
painter.drawRect(self.geometry().x(), self.geometry().y(), self.geometry().width(), self.geometry().height())


class TopWidget(QWidget):
def __init__(self):
super().__init__()
pal = QPalette()
pal.setColor(QPalette.Window, Qt.yellow)
self.setAutoFillBackground(True)
self.setPalette(pal)
def paintEvent(self, event):
painter = QPainter(self)
painter.setBrush( Qt.green )
painter.drawRect(self.x(), self.y(), self.width(), self.height())

class BottomWidget(QWidget):
def __init__(self):
super().__init__()
pal = QPalette()
pal.setColor(QPalette.Window, Qt.gray)
self.setAutoFillBackground(True)
self.setPalette(pal)
def paintEvent(self, event):
painter = QPainter(self)
painter.setBrush( Qt.blue )
painter.drawRect(self.x(), self.y(), self.width(), self.height())

def main():
app = QApplication()
containerWidget = ContainerWidget()
containerLayout = QVBoxLayout(containerWidget)
containerWidget.resize(800,600)
containerLayout.setSpacing(0)
containerLayout.setContentsMargins(0,0,0,0)


containerWidget.show()
sys.exit(app.exec_())

if __name__ == "__main__":
main()


13600

d_stranz
25th February 2021, 16:38
You are using the QWidget::geometry() to paint the rect instead of the widget's position and size (QWidget::rect())