2009-09-09 2 views
12
>>> 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' 

Да, я прочитал QString Class ReferenceКак создать QString в PyQt4?

Почему я не могу импортировать QString из QtCore, как указано в документации?

+0

Что импорта вы используете для чтения QtCore – Mark

+0

импорта SYS из PyQt4 импорта QtGui, QtCore –

ответ

7
In [1]: from PyQt4 import QtCore 
In [2]: s = QtCore.QString('foo') 
In [3]: s 
Out[3]: PyQt4.QtCore.QString(u'foo') 
+0

Примечание различный импорт - Я удивлен, что импорт не дал неверный синтаксис ошибки – Mark

+2

из PyQt4 импорта QtCore s = QtCore .QString ('foo') AttributeError: объект 'module' не имеет атрибута 'QString' У меня есть эта проблема в Py3.1. Но в Py2.5 это работает, странно ... –

+0

Возможно, PyQt4 не установлен правильно для вашего Python 3.1. Или это не поддерживает. – wRAR

1

Это зависит от вашего оператора импорта.

Если вы пишете

from PyQt4 import QtGui, QtCore 

вы должны вызвать QString с

yourstr = QtCore.QString('foo') 

Я думаю, что вы написали это:

from PyQt4.QtGui import * 
from PyQt4.QtCore import * 

Это на самом деле не рекомендуется, но вы должны позвонить Строка с:

yourstr = QString('foo') 
15

В Python 3, QString автоматически преобразуется в строку родной Python по умолчанию:

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.

http://pyqt.sourceforge.net/Docs/PyQt4/qstring.html

+0

Ссылка 404s :(. Я ожидаю, что то же самое относится и к PyQt5? – Dennis

12

От PyQt4 4.6+ в Python3 QString не существует, и вы должны использовать обычный Объекты unicode Python3 (строковые литералы). Для того, чтобы сделать это так, что ваш код будет работать как в Python 2.x и Python 3.x вы можете сделать следующее:

try: 
    from PyQt4.QtCore import QString 
except ImportError: 
    # we are using Python3 so QString is not defined 
    QString = type("") 

В зависимости от вашего случая использования вы можете уйти с этой простой хак.

Смежные вопросы