Search code examples
pythonqtpyqtstylesheet

qt stylesheet not working


So I am writing a small program,here is the code:

import sys
from PyQt5.Qt import QApplication
from PyQt5 import QtWidgets

class CMyWidget(QtWidgets.QWidget):
    def __init__(self,p = None):
        super(CMyWidget,self).__init__(p)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    #w = QtWidgets.QWidget()   #this will be ok  #1
    w = CMyWidget()                              #2
    label = QtWidgets.QLabel(w)
    label.setText("12345")
    btn = QtWidgets.QPushButton(w)
    btn.setText("X")

    hlayout = QtWidgets.QHBoxLayout(w)
    hlayout.addWidget(label)
    hlayout.addWidget(btn)
    w.setStyleSheet("border:none;"\
                "border-bottom:5px solid rgb(255,0,0)")
    w.show()
    sys.exit(app.exec_())

the problem is if i use #1,then everything is ok,all widgets's bottom border drawed;but if i change to #2,only child widget draw bottom border,the CMyWidget won't draw the bottom border,am I doing something wrong here?


Solution

  • There are some problems with stylesheets when you try to use it in derived classes. To solve your problem, try to use this:

    w = CMyWidget()    
    w.setAttribute(QtCore.Qt.WA_StyledBackground)      
    

    In this code QtCore.Qt.WA_StyledBackground means that widget should be drawn using a styled background.