2009-09-09 15 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' 

Sí, he leído QString Class Reference¿Cómo crear QString en PyQt4?

Por qué no puedo importar QString de QtCore, tal como se especifica en la documentación?

+0

Lo importación está usando para leer QtCore – Mark

+0

import sys de PyQt4 importación QtGui, QtCore –

Respuesta

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

Nota los diferentes importación - Me sorprende que su importación no dio una sintaxis no válida de error – Mark

+2

de PyQt4 importación QtCore s = QtCore .QString ('foo') AttributeError: el objeto 'module' no tiene atributo 'QString' Tengo este problema en Py3.1. Pero en Py2.5 está funcionando, extraño ... –

+0

Quizás PyQt4 no está instalado correctamente para su Python 3.1. O no lo admite. – wRAR

1

Depende de su estado de importación.

Si se escribe

from PyQt4 import QtGui, QtCore 

debe llamar QString con

yourstr = QtCore.QString('foo') 

Creo que ha escrito esto:

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

En realidad no es recomendable, pero debe llamar Cadena con:

yourstr = QString('foo') 
15

En Python 3, QString se asigna automáticamente a la cadena de Python nativo por defecto:

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

El enlace 404s :(. ¿Espero que lo mismo se aplique en PyQt5? – Dennis

12

De PyQt4 4.6+ en python3 QString no existe y que se supone que el uso ordinario Objetos Unicode Python3 (literales de cadena). Para hacer esto para que su código funcionará tanto en Python y Python 2.x 3.x se puede hacer lo siguiente:

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

Dependiendo de su caso de uso podría salirse con este sencillo truco.