pythonpyside2qframe

how to set color of frame of Qframe?


I want to set a color of the frame provide by QFrame in pyside2.

Below document provide complete details, how to create a frame with the different style, like a box, panel, Hline, etc...

https://doc-snapshots.qt.io/qtforpython/PySide2/QtWidgets/QFrame.html#detailed-description

My question is how I can set the color of that frame. I tried to set the color using "background-color" and "border" stylesheet, but not get output which I want.

Below is my code.

class HLine(QFrame):
    def __init__(self, parent=None, color="black"):
        super(HLine, self).__init__(parent)
        self.setFrameShape(QFrame.HLine)
        self.setFrameShadow(QFrame.Plain)
        self.setLineWidth(0)
        self.setMidLineWidth(3)
        self.setContentsMargins(0, 0, 0, 0)
        self.setStyleSheet("border:1px solid %s" % color)

    def setColor(self, color):
        self.setStyleSheet("background-color: %s" % color)
        pass

Out without any stylesheet.

enter image description here

Output with border style sheet

enter image description here

Out with background-color stylesheet

enter image description here

both are stylesheet giving unwanted output.

How can I set color without changing the look of the frame?


Solution

  • Instead of using Qt Style Sheet you can use QPalette:

    import sys
    from PySide2.QtCore import Qt
    from PySide2.QtGui import QColor, QPalette
    from PySide2.QtWidgets import QApplication, QFrame, QWidget, QVBoxLayout
    
    
    class HLine(QFrame):
        def __init__(self, parent=None, color=QColor("black")):
            super(HLine, self).__init__(parent)
            self.setFrameShape(QFrame.HLine)
            self.setFrameShadow(QFrame.Plain)
            self.setLineWidth(0)
            self.setMidLineWidth(3)
            self.setContentsMargins(0, 0, 0, 0)
            self.setColor(color)
    
        def setColor(self, color):
            pal = self.palette()
            pal.setColor(QPalette.WindowText, color)
            self.setPalette(pal)
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        w = QWidget()
        w.resize(400, 400)
        lay = QVBoxLayout(w)
        lay.addWidget(HLine())
    
        for color in [QColor("red"), QColor(0, 255, 0), QColor(Qt.blue)]:
            h = HLine()
            h.setColor(color)
            lay.addWidget(h)
    
        w.show()
        sys.exit(app.exec_())
    

    enter image description here