Search code examples
pythonpyqt5borderqwidgetframeless

pyqt5 border apply only to parent widget problem


Everyone. I have strange issue in pyqt5. I tried to change border but failed, I have always headache when applying border style. Here comes my code. Pls help me

from PyQt5.QtWidgets import QWidget,QApplication,QTextEdit
from PyQt5.QtCore import Qt
from PyQt5 import QtWidgets
import sys



class SomeWidget(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setStyleSheet('border:10px solid green')
        pass

class mainWidget(QWidget):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        widget = SomeWidget(self)
        widget.setWindowFlags(Qt.FramelessWindowHint|Qt.Window)
        widget.resize(self.width()//2,self.height()//2)
        
        widget.show()
        # self.setStyleSheet(styles)
        pass

def test1():
    return 0,1

if __name__ == "__main__":

    app = QApplication(sys.argv)
    mw = mainWidget()
    mw.show()
    sys.exit(app.exec_())
    
    pass

Solution

  • The issue here is that the QWidget class does not support the border property (see this answer and the Qt stylesheet documentation directly).

    That being said, changing the QWidget to a QFrame does the trick:

    import sys
    
    from PyQt5.QtCore import Qt
    from PyQt5.QtWidgets import QWidget, QApplication, QFrame
    
    
    class SomeWidget(QFrame):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.setStyleSheet('border:10px solid green')
    
    
    class mainWidget(QWidget):
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
            widget = SomeWidget(self)
            widget.setWindowFlags(Qt.FramelessWindowHint | Qt.Window)
            widget.resize(self.width() // 2, self.height() // 2)
    
            widget.show()
    
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        mw = mainWidget()
        mw.show()
    
        sys.exit(app.exec_())