How to create QString in PyQt4?
-
05-07-2019 - |
Question
>>> from PyQt4 import QtCore
>>> str = QtCore.QString('Hello')
AttributeError: 'module' object has no attribute 'QString'
>>> QtCore.QString._init_(self)
AttributeError: 'module' object has no attribute 'QString'
Yes, I've read QString Class Reference
Why can't I import QString
from QtCore
, as specified in the docs ?
Solution
In [1]: from PyQt4 import QtCore
In [2]: s = QtCore.QString('foo')
In [3]: s
Out[3]: PyQt4.QtCore.QString(u'foo')
OTHER TIPS
In Python 3, QString is automatically mapped to the native Python string by default:
The QString class is implemented as a mapped type that is automatically converted to and from a Python string. In addition a None is converted to a null QString. However, a null QString is converted to an empty Python string (and not None). (This is because Qt often returns a null QString when it should probably return an empty QString.)
The QChar and QStringRef classes are implemented as mapped types that are automatically converted to and from Python strings.
The QStringList class is implemented as a mapped type that is automatically converted to and from Python lists of strings.
The QLatin1Char, QLatin1String and QStringMatcher classes are not implemented.
From PyQt4 4.6+ in Python3 QString doesn't exist and you are supposed to use ordinary Python3 unicode objects (string literals). To do this so that your code will work in both Python 2.x AND Python 3.x you can do following:
try:
from PyQt4.QtCore import QString
except ImportError:
# we are using Python3 so QString is not defined
QString = type("")
Depending on your use case you might get away with this simple hack.
It depends on your import statement.
If you write
from PyQt4 import QtGui, QtCore
you must call QString with
yourstr = QtCore.QString('foo')
I think you've written this :
from PyQt4.QtGui import *
from PyQt4.QtCore import *
It's not really recommended, but you should call String with :
yourstr = QString('foo')