Question

We want to set a background image on a QtGui.QFrame object (in this case self). The path to the image has a Swedish Users directory called "Björn" on windows 7. The problem is the special character 'ö', which is coded as '\xf6' in py.

Test on shell:

>>>"Björn"
'Bj\xf6rn'

We would like to do this:

self.setStyleSheet("""QFrame {background: url(c:\Users\Bj\xf6rn\image.png) center no-repeat;} """)

But it does not work.

We know that it works in another directory without "special characters", but in our case we must handle a "Swedish" directory.

Any ideas, to solve this?

Was it helpful?

Solution

There are several things wrong with your stylesheet.

Firstly, you cannot use back-slashes in paths; you must use forward-slashes. Secondly, you should use quotes when including non-ascii characters. Thirdly, you should either use normal, unescaped unicode characters, or the css escaping syntax. And finally, if you're using python2, you must use unicode strings (i.e. u"") if you want to include unescaped unicode characters.

To use unescaped unicode characters, you may need to declare an encoding for your python module, depending on what version of python you are using.

For python2, with a utf-8 encoding:

# -*- coding: utf-8 -*-

self.setStyleSheet(u"""
    QFrame {background: url('c:/Users/Björn/image.png') center no-repeat;}
    """)

For python3, utf-8 is assumed by default, so no encoding declaration is needed:

self.setStyleSheet("""
    QFrame {background: url('c:/Users/Björn/image.png') center no-repeat;}
    """)

For either version, using css escapes:

self.setStyleSheet("""
    QFrame {background: url('c:/Users/Bj\\0000F6rn/image.png') center no-repeat;}
    """)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top