2

I don't seem to get the Stylesheets to work in PySide. Is there some special syntax that differs from PyQt?

Here's a small example code:

import sys
from PySide import QtGui

class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        okButton = QtGui.QPushButton("OK")
        cancelButton = QtGui.QPushButton("Cancel")
        testWidget = QtGui.QWidget()
        hbox2 = QtGui.QHBoxLayout()
        hbox2.addWidget(okButton)
        testWidget.setLayout(hbox2)
        testWidget.setObjectName("testWidget")
        testWidget.setStyleSheet("QWidget#testWidget { \n     border: 2px solid gray; \n     border-radius: 3px; \n }")
        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(testWidget)
        hbox.addWidget(cancelButton)

        self.setLayout(hbox)    
        self.setGeometry(300, 300, 300, 150)
        self.setWindowTitle('Expample')    
        self.show()

app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

The result is:

PySide

If I change from PySide import QtGui to from PyQt4 import QtGui, I receive the following result:

PyQt4

Why doesn't the Stylesheet work in PySide?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Jakube
  • 3,353
  • 3
  • 23
  • 40

1 Answers1

3

The QWidget class may be treated differently when it comes to stylesheets. To get your example to work correctly, you need to explicitly enable the stylesheet like this:

    testWidget.setAttribute(QtCore.Qt.WA_StyledBackground)

However, I don't exactly know why PyQt and PySide behave differently in this regard. This mailing-list post from the author of PyQt:

suggests that it is only subclasses of QWidget that should need to set the WA_StyledBackground attribute. And indeed if testWidget is replaced by such a subclass:

class SubWidget(QtGui.QWidget): pass
...
testWidget = SubWidget()        
# testWidget.setAttribute(QtCore.Qt.WA_StyledBackground)

then the example no longer works in either PyQt or PySide.

This means that the PySide behaviour is wrong for non-subclasses of QWidget. Possibly there is some kind of meta-object bug which is making the PySide QWidget class look like a subclass to Qt.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • Thanks. Just stumbled about this rather similar question: http://stackoverflow.com/questions/24653405/why-is-qwidget-with-border-and-background-image-styling-behaving-different-to-ql There Chris recommends using `QFrame` instead of `QWidget`. It's a lot simpler and cleaner than enabling the style-sheets. Especially since I use the Qt Designer in combination with `uic` / `pyside-uic`. – Jakube Sep 01 '15 at 07:05