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

Ja, ich habe QString Class Reference lesenWie erstelle ich QString in PyQt4?

Warum kann ich importieren nicht QString von QtCore, wie es in der Dokumentation angegeben?

+0

Welcher Import verwenden Sie QtCore – Mark

+0

import sys von PyQt4 Import QtGui, QtCore –

Antwort

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

Beachten Sie den verschiedene Import zu lesen - ich bin überrascht, dass der Import nicht gab einem ungültigen Syntaxfehler – Mark

+2

von PyQt4 Import QtCore s = QtCore .QString ('foo') AttributeError: 'Modul' Objekt hat kein Attribut 'QString' Ich habe dieses Problem in Py3.1. Aber in Py2.5 funktioniert es, komisch ... –

+0

Vielleicht ist PyQt4 nicht richtig für Python 3.1 installiert. Oder es unterstützt es nicht. – wRAR

1

Es hängt von Ihrer Importaussage ab.

Wenn Sie

from PyQt4 import QtGui, QtCore 

schreiben müssen Sie QString rufen mit

yourstr = QtCore.QString('foo') 

Ich glaube, du hast dies geschrieben:

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

Es ist nicht wirklich zu empfehlen, aber man sollte rufen Zeichenkette mit:

yourstr = QString('foo') 
15

In Python 3 wird QString automatisch auf die native Python-String standardmäßig zugeordnet:

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

Der Link 404s :(. Ich erwarte das gleiche gilt in PyQt5? – Dennis

12

Von PyQt4 4.6+ in Python3 QString existiert nicht und Sie sollen gewöhnlichen verwenden Python3-Unicode-Objekte (String-Literale). Um dies zu tun, so dass Ihr Code sowohl in Python 2.x funktionieren und Python 3.x können Sie wie folgt vorgehen:

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

auf Ihren Anwendungsfall Je könnten Sie mit diesem einfachen Hack wegzukommen.