2009-09-09 20 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ì, ho letto QString Class ReferenceCome creare QString in PyQt4?

Perché non è possibile importare QString da QtCore, come specificato nella documentazione?

+0

Cosa importazione stai usando per leggere QtCore – Mark

+0

import sys da PyQt4 importazione QtGui, QtCore –

risposta

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 la diversa import - Mi sorprende che l'importazione non ha dato errore – Mark

+2

una sintassi non valida dal PyQt4 importazione QtCore s = QtCore .QString ('foo') AttributeError: l'oggetto 'module' non ha attributo 'QString' Ho questo problema in Py3.1. Ma in Py2.5 funziona, strano ... –

+0

Forse PyQt4 non è installato correttamente per il tuo Python 3.1. O non lo supporta. – wRAR

1

Dipende dalla dichiarazione di importazione.

Se si scrive

from PyQt4 import QtGui, QtCore 

è necessario richiamare QString con

yourstr = QtCore.QString('foo') 

Penso che hai scritto questo:

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

Non è davvero consigliabile, ma si dovrebbe chiamare Stringa con:

yourstr = QString('foo') 
15

In Python 3, QString è mappato automaticamente alla stringa di Python nativo di 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.

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

+0

Il link 404s :(. Mi aspetto lo stesso vale per PyQt5? – Dennis

12

Da PyQt4 4.6+ in python3 QString non esiste e si suppone di utilizzare ordinaria Oggetti unicode Python3 (stringhe letterali). Per fare questo in modo che il codice funziona sia in 2.x Python e Python 3.x si può fare seguente:

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

A seconda del caso d'uso si potrebbe ottenere via con questo semplice trucco.