动态GUI页面属性错误

时间:2014-12-03 08:01:23

标签: python attributes pyqt4

我有一个GUI页面,其中填充了所需数量的具有唯一名称的lineedit框。我想稍后使用该名称将文本分配给相应的lineedit框。这是代码:

from PyQt4 import QtCore, QtGui
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_LoadsForm3_1(object):
    def setupUi(self, LoadsForm3_1):
        LoadsForm3_1.setObjectName(_fromUtf8("LoadsForm3_1"))
        LoadsForm3_1.resize(500, 500)
        self.scrollArea = QtGui.QScrollArea(LoadsForm3_1)
        self.scrollArea.setGeometry(QtCore.QRect(20, 180, 450, 250))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
        self.scrollAreaWidgetContents = QtGui.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, -293, 250, 500))
     self.scrollAreaWidgetContents.setObjectName(_fromUtf8("scrollAreaWidgetContents"))
        self.gridLayout = QtGui.QGridLayout(self.scrollAreaWidgetContents)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))

        for i in range (0,10):
            lE="lE0"+str(i)+"_P01"+"E0"+str(i)
            self.lE =QtGui.QLineEdit(self.scrollAreaWidgetContents)
            self.lE.setObjectName(_fromUtf8(lE))
            self.gridLayout.addWidget(self.lE, i, 1, 1, 1)
            self.scrollArea.setWidget(self.scrollAreaWidgetContent
        self.lE01_P01E01.setText("xyz")

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

但是在执行时它是syas:AttributeError:'Ui_LoadsForm3_1'对象没有属性'lE01_P01E01'。我是Pyqt4的新手,我使用的是python 2.7。任何帮助表示赞赏。感谢!!!

1 个答案:

答案 0 :(得分:1)

您的代码有点混乱。您将属性lE设置为'lE01_P01E01',将self.lE设置为QLineEdit对象,但是您从未设置self.lE01_P01E01因此它不存在当你尝试设置它的文本时。你的意思可能是:

    for i in range(1,10):
        lE = QtGui.QLineEdit(self.scrollAreaWidgetContents)
        lE.setObjectName(_fromUtf8(lE))
        self.gridLayout.addWidget(lE, i, 1, 1, 1)

        # e.g. set self.lE01_P01E01 to lE
        setattr(self, 'lE0' + str(i) + '_P01E0' + str(i), lE)

        self.scrollArea.setWidget(self.scrollAreaWidgetContent

    self.lE01_P01E01.setText("xyz")

但是,您应该编辑自动生成的UI文件,因为它将被覆盖。而是从另一个.py文件like this.

中调用它