我正在尝试使用 PyQt4 创建一个 GUI,我最初使用 QT 设计器来完成我的整体布局,然后修改代码。我注意到的是,有很多重复的代码将被替换为一个类或方法,但我不确定哪个会更好,或者如何正确地实现任何一种方式。这是重复代码的示例(它是一个非常大的程序)
self.ch2_R = QtGui.QLineEdit(Form)
self.ch2_R.setSizePolicy(sizePolicy)
self.ch2_R.setText(_fromUtf8(""))
self.ch2_R.setFrame(True)
self.ch2_R.setAlignment(QtCore.Qt.AlignCenter)
self.ch2_R.setReadOnly(True)
self.ch2_R.setObjectName(_fromUtf8("ch2_R"))
print self.ch2_R
self.ch3_R = QtGui.QLineEdit(Form)
self.ch3_R.setSizePolicy(sizePolicy)
self.ch3_R.setText(_fromUtf8(""))
self.ch3_R.setFrame(True)
self.ch3_R.setAlignment(QtCore.Qt.AlignCenter)
self.ch3_R.setReadOnly(True)
self.ch3_R.setObjectName(_fromUtf8("ch3_R"))
self.ch4_R = QtGui.QLineEdit(Form)
self.ch4_R.setSizePolicy(sizePolicy)
self.ch4_R.setText(_fromUtf8(""))
self.ch4_R.setFrame(True)
self.ch4_R.setAlignment(QtCore.Qt.AlignCenter)
self.ch4_R.setReadOnly(True)
self.ch4_R.setObjectName(_fromUtf8("ch4_R"))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ch2_R.sizePolicy().hasHeightForWidth())
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ch3_R.sizePolicy().hasHeightForWidth())
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ch4_R.sizePolicy().hasHeightForWidth())
self.gridLayout.addWidget(self.ch2_R, 4, 5, 1, 4)
self.gridLayout.addWidget(self.ch3_R, 5, 5, 1, 4)
self.gridLayout.addWidget(self.ch4_R, 6, 5, 1, 4)
这段代码都在
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_Form(object):
def setupUi(self, Form):
我最初的尝试是像这样在 Ui_Form 类中创建一个方法
def myQtlineEdit(self, name, form, sizePolicy):
self.name = QtGui.QLineEdit(Form)
self.name.setSizePolicy(sizePolicy)
self.name.setText(_fromUtf8(""))
self.name.setFrame(True)
self.name.setAlignment(QtCore.Qt.AlignCenter)
self.name.setReadOnly(True)
self.name.setObjectName(_fromUtf8("%s" %name))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.name.sizePolicy().hasHeightForWidth())
self myQtlineEdit("ch2_R", form, sizePolicy)
它确实创建了我正在寻找的文本字段,但是
self.gridLayout.addWidget(self.ch2_R, 4, 5, 1, 4)
会给我一个错误,说 ch2_R 不存在
谢谢。