Search code examples
pythonpyqtpyqt4pyqt5pyside

How to paint RoundedRect border outline the same width all around in PyQt / PySide?


I have been searching for this answer for quite awhile actually and I have seen other posts in the past asking the same thing but I never came across any good answers.
Anyway, if you run my code you will see that the 4 edges have a thicker border than the rest of the outline. Is it possible to have a nice even border all around?

import sys
from PySide2.QtCore import Qt
from PySide2.QtGui import QPainter, QPen, QColor, QBrush
from PySide2.QtWidgets import QWidget, QApplication

class MainWindow(QWidget):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground, True)

    def paintEvent(self, event):
        painter = QPainter(self)
        fillColor = QColor(255, 165, 0, 180)
        lineColor = QColor(0, 0, 0, 255)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QPen(QBrush(lineColor), 2))
        painter.setBrush(QBrush(fillColor))
        painter.drawRoundedRect(self.rect(), 15, 15)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    app.exec_()

Thanks.


Solution

  • Try it:

    import sys
    from PyQt5.QtCore    import Qt,                              QRectF
    from PyQt5.QtGui     import QPainter, QPen, QColor, QBrush,  QPainterPath
    from PyQt5.QtWidgets import QWidget, QApplication
    
    class MainWindow(QWidget):
        BorderColor     = QColor(0, 0, 0, 255)     
        BackgroundColor = QColor(255, 165, 0, 180) 
    
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
            self.setWindowFlags(Qt.FramelessWindowHint)          
            self.setAttribute(Qt.WA_TranslucentBackground, True) 
    
        def paintEvent(self, event):
            super(MainWindow, self).paintEvent(event) 
    
            painter = QPainter(self)
            painter.setRenderHint(QPainter.Antialiasing)   
    
            rectPath = QPainterPath()                      
            height = self.height() - 8                     
            rectPath.addRoundedRect(QRectF(2, 2, self.width()-4, height), 15, 15)
            painter.setPen(QPen(self.BorderColor, 2, Qt.SolidLine,
                                     Qt.RoundCap, Qt.RoundJoin))
            painter.setBrush(self.BackgroundColor)
            painter.drawPath(rectPath)
            painter.setPen(QPen(self.BackgroundColor, 2,
                                     Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        w = MainWindow()
        w.show()
        app.exec_()
    

    enter image description here