Search code examples
pythonqpainterpyside2

My QPainter neither draws the lines nor throws an error, how can I fix this?


Basically I'm trying to draw a border around my frameless window. It's size is 550 and 407. I create my QPainter then my lines and in the end I'm trying to draw them.

def draw_border(self):
    painter = QPainter()
    painter.begin(self)
    pen = QPen(QColor(255, 1, 1))
    painter.setPen(pen)
    left = QLine(0, 0, 0, 407)
    bottom = QLine(0, 407, 550, 407)
    right = QLine(550, 407, 550, 0)
    painter.drawLine(left)
    painter.drawLine(bottom)
    painter.drawLine(right)
    painter.end()

I expect to have three lines: left, right and bottom, but instead nothing happens.


Solution

  • I can not know where the error is because you do not provide an MCVE, so I will only propose my solution that is to reuse the rect() of the widget so the lines will adapt to the size of the window:

    from PySide2 import QtGui, QtCore, QtWidgets
    
    
    class Widget(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)
    
        def paintEvent(self, event):
            painter = QtGui.QPainter(self)
            pen = QtGui.QPen(QtGui.QColor(255, 1, 1))
            painter.setPen(pen)
            width = pen.width()
            rect = self.rect().adjusted(0, -width, -width, -width)
            painter.drawRect(rect)
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        w = Widget()
        w.resize(550, 407)
        w.show()
        sys.exit(app.exec_())