Search code examples
python-2.7qtunicodepyqtqcombobox

How can I add an item with unicode characters to a QComboBox in python?


I am trying to add prefixed units to a QComboBox in python, depending on the range of the parameter. The problem is that when I try to add a "μ" it comes out as "Î1/4" which is not what I want.

The code I am currently using is:

def build_unit_box(self, measure):
    listed = []
    if measure in {'P', 'frep'}:
        for pref in ['', 'k', 'M', 'G']:
            listed.append(str(pref + units.get(measure)))
        exec("%s" % 'self.unit_' + measure + '.addItems(listed)')
    elif measure in {'W', 'lambda', 'tau'}:
        for pref in ['', 'm', u'\u03bc'.encode('utf-8'), 'n']:
            print pref
            listed.append(str(pref + units.get(measure)))
        exec("%s" % 'self.unit_' + measure + '.addItems(listed)')

If I type print u'\u03bc' the correct character is printed.

How can I solve this?


Solution

  • I found the problem. As i had copy-pasted some of the code from another function, I was typecasting the characters to str which resulted in the wrong encoding. It works perfectly with:

    def build_unit_box(self, measure):
        listed = []
        if measure in {'P', 'frep'}:
            for pref in ['', 'k', 'M', 'G']:
                listed.append(str(pref + units.get(measure)))
            exec("%s" % 'self.unit_' + measure + '.addItems(listed)')
        elif measure in {'W', 'lambda', 'tau'}:
            for pref in ['', 'm', u'\u03bc', 'n']:
                print pref
                listed.append(unicode(pref + units.get(measure)))
            exec("%s" % 'self.unit_' + measure + '.addItems(listed)')