我有两个模块test.py和fill_combobox.py。 fill_combobox用于组合框中的默认值。模块之间的通信仍然存在问题。
test.py
from PyQt4 import QtCore, QtGui import fill_combobox 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_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(400, 300) self.comboBox = QtGui.QComboBox(Form) self.comboBox.setGeometry(QtCore.QRect(160, 120, 51, 25)) self.comboBox.setObjectName(_fromUtf8("comboBox")) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Form", None)) fill_combobox.fill() if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Form = QtGui.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_())
fill_combobox.py
def fill(): import test for i in range(40): test.Ui_Form.comboBox.addItems(str(i))
答案 0 :(得分:2)
在您的代码中行:
test.Ui_Form.comboBox.addItems(str(i))
正在访问类 Ui_Form
,而不是Ui_Form
实例。因此,该类不具有任何comboBox
属性。如果您想使用Ui_Form
类,请使用test.py
末尾显示的模式:
form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(form)
form.show()
您应该将代码放在 for
循环之前,并在循环中访问form
实例。
如果您在很多地方这样做,最好将自定义小部件编写为:
class MyWidget(QWidget, Ui_Form):
def __init__(self, parent=None, ...):
super(MyWidget, self).__init__(parent)
self.setupUi(self)
然后,您可以避免创建Ui_Form
实例,只需执行:
form = MyWidget()
form.show()