Search code examples
pythonqtcolorsstylesheet

Qt - Format QColor to be used in Style Sheet?


In my PyQt4 program, I retrieve a QColor from the User via QColorDialog.
I then need to format this QColor to be used in a Style Sheet, which I currently achieve by calling...

QColor.name()

... which returns something like '#00ff00' which would then undergo simple string manipulation to be set as a style sheet for a widget. eg:

QWidget.setStyleSheet( '* { background-color: '+ QColor.name() + ' }')

Later in the program, the background color of the widget must be fetched (using .styleSheet() and more simple string manipulation) and converted to a string which when eval()ed, would construct a QColor of the identical color.

It must be converted to a QColor, since it is later used in a QBrush. The QColor must be converted to a one line string because it is written to file, and imported from said file via eval().
(The string when eval()ed must pass the color to the QColor constructor, since the string is only one line).

In the end, I need something similiar (though not possible in this manner) like this:

ColorString = str( QtGui.QColorDialog.getColor().name() )
EvalString = "QtGui.QColor(" + ColorString +")"

Ofcourse, this method doesn't work because the QColor constructor does not accept such a format as '#00ff00' which is the format that QColorDialog.name() gives and which a QWidget.setStyleSheet() accepts.

How can I actually achieve this?

Is there anyway to convert a string like '#00ff00' to 3 integers representing Red, Green and Blue which could then be sent to the QColor constructor?
Thanks!

Note:
I realise that such a format '#00ff00' does involve a representation of those three colours, but I don't understand what 'ff' means, and calling .red() on a QColor does not return the integer that is suggested by the '#00ff00' format.
It's probably obvious that I don't understand colors :)

Specs:
- PyQt4
- Python 2.7
- Windows 7


Solution

  • Try QColor.setNamedColor(name)

    Example:

    string_with_color = '#00ff00'  # gathered somehow
    
    color = QtGui.QColor(0, 0, 0)
    color.setNamedColor(string_with_color)
    

    but I don't understand what 'ff' means

    ff = 255 in hexadecimal system

    EDIT

    As appears from the comments, solution was to convert Python string to QString

    EvalString = "QtGui.QColor(QtCore.QString(" + ColorString +"))"