[PyQt] QString and unicode problems

Andrei Kopats hlamer at tut.by
Tue Oct 18 10:07:24 BST 2011


Hi

I am developing PyQt app now, and I very often have crashes, connected with
QString usage. There are 2 reasons for exceptions:
- QString contains unicode characters
- python method called for Qt string. Sometimes called somewhere deep in
3rdparty code, such as os.path.blabla(QString))
See code examples at the end

It is easy to forget about QString conversions, because there are a few
different cases:
- if you define string in Python code - it is Python string
- if you take it from PyQt4 - it is QString
- If you passed Python string through signal-slot - it becomes QString.

The majority of methods may be called with either Python and Qt strings and
work fine.
Some bugs are not reproduced, while you use ascii, but, are reproduced, when
your user uses unicode
Too difficult, too lot of problems

QString problem wad discussed there:
http://thread.gmane.org/gmane.comp.python.pyqt-pykde/4037/
Now, when PyQt4 is widely used, it maybe to late to drop QString, because
some people use QString::endsWith(), and, probably, other compatibility
problem way happen.

But, maybe it is possible to renew this discussion and create something like
hybrid object, which is Python unicode string, but, has endsWith method (and
others, if there are API differences), so may pretend to be a QString



Code examples:
Problem 1:
In [1]: from PyQt4.QtCore import QString
In [2]: print QString('hello')
hello
In [3]: print QString('привет')  # Cyrillic symbols here
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
/home/a/code/mbox/core/src/lin/libonvif/<ipython console> in <module>()
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-11:
ordinal not in range(128)
Problem 2:
In [1]: from PyQt4.QtGui import QApplication, QFileDialog
In [2]: a = QApplication([])
In [3]: path = QFileDialog.getOpenFileName()
In [4]: path
Out[4]:
PyQt4.QtCore.QString(u'/home/a/code/mbox/core/src/lin/libonvif/Makefile')
In [5]: import os.path
In [6]: os.path.basename(path)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/home/a/code/mbox/core/src/lin/libonvif/<ipython console> in <module>()
/usr/lib/python2.7/posixpath.pyc in basename(p)
    110 def basename(p):
    111     """Returns the final component of a pathname"""
--> 112     i = p.rfind('/') + 1
    113     return p[i:]
    114
AttributeError: 'QString' object has no attribute 'rfind'

Best Regards,
Andrei Kopats,
https://github.com/hlamer/mksv3
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20111018/3d88380a/attachment-0001.html>


More information about the PyQt mailing list