Stylesheet Does Not Work Properly In Pyqt
Solution 1:
There are some issues related to propagation of stylesheets, especially for complex widgets that use scroll areas (or inherit from them).
Unfortunately, due to the complexity of style propagation and stylesheet management, it's really hard to track down the exact source of the problem, and some number of Qt bug reports exist about this matter.
First of all, it's better to have a single and centralized stylesheet: whenever you have to modify a single property that might be shared among lots of widgets, you don't have to modify the stylesheet of every widget. The drawback is that if you have many different styled widgets of the same class type, you need to better use selectors (the #
selector is the best choice, as it uses the object name of the widget to identify it, and object names are usually unique); read more about Qt stylesheet selectors.
If your program has only a single main window (and everything else is a child of it, including dialogs), you can set the stylesheet on that window, otherwise it's better to set the stylesheet on the QApplication instead.
Then, whenever those issues occur, a possible solution is to set again the stylesheet as soon as the widget is shown. For simple cases, you can try the following:
classMainWindow(QMainWindow):
shown = Falsedef__init__(self, parent=None):
super(MainWindow, self).__init__(parent=parent)
self.ui = UI()
self.ui.setupUi(self)
defshowEvent(self, event):
super().showEvent(event)
ifnot self.shown:
self.shown = True
self.ui.setStyleSheet(self.ui.styleSheet())
Unlike other properties for which Qt ignores the new value if it's identical to the current, every call to setStyleSheet()
causes the whole widget (and its children) to repolish them, even if the style sheet is empty.
Finally, it's better to avoid stylesheets that are too generic, as they might cause unexpected behavior (I know it's not your case, but it's an important aspect that should always be kept in mind). So, the following should be avoided or, at least, used with care:
setStyleSheet('color: somecolor; border: someborder')
setStyleSheet('QWidget { color: somecolor; border: someborder; }')
setStyleSheet('* { color: somecolor; border: someborder; }')
Post a Comment for "Stylesheet Does Not Work Properly In Pyqt"