[PyQt] QMessageBox with unicode text fails
David Boddie
david at boddie.org.uk
Thu Oct 25 01:52:07 BST 2007
On Wed Oct 24 23:03:20 BST 2007, Tim Welch wrote:
> I'm trying to display a unicode string in a QMessageBox using the
> information() static method. However it seems to only accept ascii
> characters. I'm using qt/pyqt 4.3.0 on Windows.
>
> Here's a sample app with output:
>
> # *-* coding: utf-8 *-*
> from PyQt4 import QtCore, QtGui
> from PyQt4.QtCore import *
> from PyQt4.QtGui import *
>
> if __name__ == "__main__":
> qapp = QApplication([])
> QMessageBox.critical(None, "ImportError", unicode("blort español"))
> sys.exit(qapp.exec_())
First of all, are you sure that the syntax you've used for the encoding
directive is correct?
http://docs.python.org/tut/node4.html
Otherwise, this looks fine, but there's potentially a nasty surprise lurking
in there. Even if I change the comment line to reflect the syntax used in
the above document, I still see this error:
> ********************************************************
>
> Traceback (most recent call last):
> File "U:\dev\delphos\src\gui\test.py", line 8, in <module>
> QMessageBox.critical(None, "ImportError", unicode("blort español"))
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 10:
> ordinal not in range(128)
>
> *********************************************************
This error is due to the way Python's unicode() function is asked to handle
the string you've given it, and is unrelated to PyQt's string handling.
The proper way to deal with this is to ensure that you're using Unicode
strings. It turns out that you can just write
QMessageBox.critical(None, "ImportError", u"blort español")
and everything should work as expected.
Experimenting a bit further, and making a few late-night assumptions about
the way things work, it seems that the following happens when you use
non-Unicode strings in your code:
1. Python reads in the source code, encoded as UTF-8.
2. When run, the unicode() call is asked to decode UTF-8 encoded text
but hasn't been told which encoding to use, so it falls back on
the default one.
3. The default encoding isn't UTF-8, so it doesn't work.
Since it appears that the encoding used isn't set by the presence of the
encoding hint, you would need to force the conversion by explicitly passing
the encoding to the unicode() method or, alternatively, somehow setting
the default encoding to UTF-8. However, I think the proper solution is as
I describe above: to write the string as a Unicode string and to let Python
decode it when it loads the file.
> Removing the ñ creates a working message box. It makes no difference if I
> use the static method or create and setup a QMessageBox object myself. Any
> help is appreciated, I found no mention of this in any documentation or the
> archives.
It's a Python thing. I expect that a new person finds out about this the
hard way every day. :-)
David
More information about the PyQt
mailing list