Python 3:PyQt4上的QString

时间:2012-04-14 02:22:28

标签: pyqt4 qstring python-3.2

我在尝试使用非常简单的用户界面时遇到问题。我用Qt Designer制作了我的UI,然后用pyuic4我得到了我的python代码。然后我编写了我需要的函数,并使用Eclipse IDE编译。

我从pyuic4获得的代码是:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Dni.ui'
#
# Created: Sat Apr 14 02:44:34 2012
#      by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(371, 217)
        Dialog.setMinimumSize(QtCore.QSize(371, 217))
        self.layoutWidget = QtGui.QWidget(Dialog)
        self.layoutWidget.setGeometry(QtCore.QRect(30, 30, 311, 151))
        self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
        self.gridLayout = QtGui.QGridLayout(self.layoutWidget)
        self.gridLayout.setMargin(0)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.label = QtGui.QLabel(self.layoutWidget)
        self.label.setObjectName(_fromUtf8("label"))
        self.horizontalLayout.addWidget(self.label)
        self.entrada = QtGui.QLineEdit(self.layoutWidget)
        self.entrada.setObjectName(_fromUtf8("entrada"))
        self.horizontalLayout.addWidget(self.entrada)
        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.boton = QtGui.QPushButton(self.layoutWidget)
        self.boton.setObjectName(_fromUtf8("boton"))
        self.gridLayout.addWidget(self.boton, 1, 0, 1, 1)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.label_3 = QtGui.QLabel(self.layoutWidget)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.horizontalLayout_2.addWidget(self.label_3)
        self.salida = QtGui.QLineEdit(self.layoutWidget)
        self.salida.setObjectName(_fromUtf8("salida"))
        self.horizontalLayout_2.addWidget(self.salida)
        self.gridLayout.addLayout(self.horizontalLayout_2, 2, 0, 1, 1)
        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("Dialog", "Introduzca su DNI", None, QtGui.QApplication.UnicodeUTF8))
        self.boton.setText(QtGui.QApplication.translate("Dialog", "Hallar NIF", None, QtGui.QApplication.UnicodeUTF8))
        self.label_3.setText(QtGui.QApplication.translate("Dialog", "NIF:", None, QtGui.QApplication.UnicodeUTF8))


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Dialog = QtGui.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

我用我需要的函数编写的代码:

from Dni import Ui_Dialog
from PyQt4 import QtCore, QtGui

LETRADNI = {0:'T', 1:'R', 2:'W', 3:'A', 4:'G', 5:'M', 6:'Y', 7:'F', 8:'P', 9:'D', 10:'X', 11:'B', 12:'N',
            13: 'J', 14:'Z', 15:'S', 16:'Q', 17:'V', 18:'H', 19:'L', 20:'C', 21:'K', 22:'E'}


# Se hereda de la clase QtGui.QMainWindow
class Principal(QtGui.QMainWindow):
    # Se define el constructor de la clase __init__
    def __init__(self):
        # Se llama al constructor de la clase padre
        QtGui.QMainWindow.__init__(self)

        # Se crea la instancia de Ui_Dialog
        self.ventana = Ui_Dialog()
        self.ventana.setupUi(self)

        # Se conectan las señales con los slots
        self.connect(self.ventana.boton,QtCore.SIGNAL('clicked()'), self.letradni)


def Calcula_letra_dni(dni):
    '''Función Calcula_letra_dni:

        Funcionamiento:

            La función recibe el valor entero dni. Posteriormente calculará el resto de la división
            por 23. Éste número se buscará en el diccionario 'LETRADNI' para obtener la letra correspondiente
            a ese DNI.

        Argumentos

            dni -- número del documento nacional de identidad (int)

        Devuelve:

            Una cadena (string) -- DNI + letra preparado para salida por pantalla
    '''
    #if len(str(dni))>8 & len(str(dni))<7:
    #    raise ValueError('El dni debe tener entre 7 y 8 cifras')

    num_letra = dni % 23.0

    letra = LETRADNI[num_letra]

    return '{0}-{1}'.format(dni,letra)


def letradni(self):
    self.ventana.salida.setText(Calcula_letra_dni(self.ventana.entrada.text()))

第一个编译并运行,它完美地显示了我的ui。

编译第二个我得到的错误是:

Description                                 Resource  Path  Location   Type
Undefined variable from import: QString Dni.py    /Dni  line 18    PyDev Problem

任何人都可以帮助我吗?

提前致谢。

1 个答案:

答案 0 :(得分:2)

首先,我认为您实际列出的问题与Eclipse,pydev和您的项目PYTHONPATH有关。检查这一点以确保您已正确设置所有内容并在pythonpath中包含PyQt4:
http://popdevelop.com/2010/04/setting-up-ide-and-creating-a-cross-platform-qt-python-gui-application/

之后,除了你提到的内容之外,你的代码似乎有些问题......

首先定义Principal类,然后定义Calcula_letra_dni函数,然后定义类似于letradni的类实例方法Principal

class Principal(QtGui.QMainWindow):
    # Se define el constructor de la clase __init__
    def __init__(self):
        ...

    def letradni(self):
        ...


def Calcula_letra_dni(dni):
    ...

然后,当您尝试对字符串(感谢@Avaris)进行数学运算并浮动时,您将会引发异常:
num_letra = dni % 23.0

您应该首先将该字符串转换为浮点数:num_letra = float(dni) % 23.0

最后,我想您也忘了为您的应用定义main。你有Dni.py中自动生成的那个,但你没有为你的实际入口点脚本写一个:

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    form = Principal()
    form.show()
    sys.exit(app.exec_())