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

Tak, czytałem QString Class ReferenceJak utworzyć QString w PyQt4?

Dlaczego nie mogę importować QString z QtCore, jak określono w docs?

+0

Co import używasz czytać QtCore – Mark

+0

import sys z PyQt4 importowej QtGui, QtCore –

Odpowiedz

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

zanotować inny import - Dziwię się, że import nie dają nieprawidłowy Błąd składni – Mark

+2

z PyQt4 importowej QtCore s = QtCore .QString ('foo') AttributeError: obiekt 'module' nie ma atrybutu 'QString' Mam ten problem w Py3.1. Ale w Py2.5 działa, dziwne ... –

+0

Może PyQt4 nie jest poprawnie zainstalowany dla twojego Pythona 3.1. Lub nie obsługuje go. – wRAR

1

To zależy od wyciągu importu.

Jeśli piszesz

from PyQt4 import QtGui, QtCore 

należy zadzwonić QString z

yourstr = QtCore.QString('foo') 

Chyba pisałem tak:

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

To naprawdę nie jest zalecane, ale należy zadzwonić Łańcuch z:

yourstr = QString('foo') 
15

W Pythonie 3, QString jest automatycznie odwzorowywane na rodzimym Python ciąg domyślnie:

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

Łącze 404s :(. Spodziewam się, że to samo dotyczy PyQt5? – Dennis

12

Od PyQt4 4.6+ w Python3 QString nie istnieje, a ci mają wykorzystywać zwykłe Python3 unicode objects (literały łańcuchowe). Aby to zrobić tak, że kod będzie działał zarówno 2.x Python i Python 3.x można wykonać następujące czynności:

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

zależności od przypadku użycia może uciec z tego prostego hack.