kragor kragor - 16 days ago 7
Python Question

explicitly setting style sheet in python pyqt4?

In pyqt standard way for setting style sheet is like this:

MainWindow.setStyleSheet(_fromUtf8("/*\n"
"gridline-color: rgb(85, 170, 255);\n"
"QToolTip\n"
"{\n"
" border: 1px solid #76797C;\n"
" background-color: rgb(90, 102, 117);;\n"
" color: white;\n"
" padding: 5px;\n"
" opacity: 200;\n"
"}\n"
"#label_3{\n"
" background-color:rgb(90, 102, 117);\n"
" color:white;\n"
" padding-left:20px;\n"
" \n"
"}\n"
"#label_2{\n"
" color:white;\n"
" padding-left:20px;\n"
" \n"
"}\n"


But like we link the stylesheet in html
<link rel="stylesheet" href="style.css">

.can't we do the same in pyqt?It helps in organizing the things.

Answer

There are currently only two main ways to set a stylesheet. The first is to use the setStyleSheet method:

widget.setStyleSheet("""
    QToolTip {
        border: 1px solid #76797C;
        background-color: rgb(90, 102, 117);
        color: white;
        padding: 5px;
        opacity: 200;
    }
    """)

This will only take a string, so an external resource would need to be explicitly read from a file, or imported from a module.

The second method is to use the -stylesheet command-line argument, which allows an external qss resource to be specified as a path:

python myapp.py -stylesheet style.qss

This opens up the possibility of a tempting hack, since it is easy enough to manipulate the args passed to the QApplication constructor, and explicitly insert a default stylesheet:

import sys

args = list(sys.argv)
args[1:1] = ['-stylesheet', 'style.qss']

app = QtGui.QApplication(args)

(Inserting the extra arguments at the beginning of the list ensures that it is still possible for the user to override the default with their own stylesheet).

Comments