我正在尝试编写PyQt5应用程序。列表变量中的所有列表项都是表单的LineEdit对象。在调用复位函数时,我希望将它们设置为我尝试编写for循环而不是硬编码的特定值。
但是,我不能将变量中的列表项用作对象,因为它们是其他文件中的对象属性并且正在执行
self.eval(variables[i]).setText(default_0_values[i])
无效,因为eval不是self的属性。 但是,如果我跑
self.nGASLineEdit.setText(2)
有效。但我似乎无法自动化它而且我被卡住了。需要解决这个问题。
from PyQt5 import QtCore,QtGui,QtWidgets,uic
variables=[
'nGASLineEdit','nDELTALineEdit','iMIPLineEdit','nDVECLineEdit','nSEEDLineEdit','eSTARTLineEdit','eTHRMLineEdit','eCUTLineEdit','nGAS1LineEdit','nGAS2LineEdit','nGAS3LineEdit','nGAS4LineEdit','nGAS5LineEdit','nGAS6LineEdit','fRAC1LineEdit','fRAC2LineEdit','fRAC3LineEdit','fRAC4LineEdit','fRAC5LineEdit','fRAC6LineEdit','tEMPLineEdit','tORRLineEdit','eFIELDLineEdit','bMAGLineEdit','bTHETALineEdit','iWRITELineEdit','iPENLineEdit','dETEFFLineEdit','eXCWGHTLineEdit','kGASLineEdit','lGASLineEdit','lCMPLineEdit','lRAYLineEdit','lPAPLineEdit','lBRMLineEdit','iECASCLineEdit'
]
default_0_values=[
2,100,5,1,0,1.0,1.5,2.0,
2 ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
]
class Window(QtWidgets.QMainWindow):
def __init__(self):
super(Window,self).__init__()
uic.loadUi('main.ui',self)
self.pushButton_2.clicked.connect(lambda: self.reset())
def select_func(self,func_name):
return func_name
def reset(self):
global variables
global default_0_values
for i in range(len(variables)):
self.eval(variables[i]).setText(default_0_values[i])
if __name__=='__main__':
import sys
app=QtWidgets.QApplication(sys.argv)
window=Window()
window.show()
sys.exit(app.exec())
答案 0 :(得分:2)
使用eval
是一种糟糕的编程习惯,在这种情况下它是不必要的,除了放self.eval(...)
这些表明eval是Window类的一个函数,显然它不是..另一方面,如果您只读取变量,则不必使用global
。相反,我们可以使用getattr()
,如下所示:
from PyQt5 import QtCore,QtGui,QtWidgets,uic
variables=['nGASLineEdit','nDELTALineEdit','iMIPLineEdit','nDVECLineEdit','nSEEDLineEdit','eSTARTLineEdit','eTHRMLineEdit','eCUTLineEdit','nGAS1LineEdit','nGAS2LineEdit','nGAS3LineEdit','nGAS4LineEdit','nGAS5LineEdit','nGAS6LineEdit','fRAC1LineEdit','fRAC2LineEdit','fRAC3LineEdit','fRAC4LineEdit','fRAC5LineEdit','fRAC6LineEdit','tEMPLineEdit','tORRLineEdit','eFIELDLineEdit','bMAGLineEdit','bTHETALineEdit','iWRITELineEdit','iPENLineEdit','dETEFFLineEdit','eXCWGHTLineEdit','kGASLineEdit','lGASLineEdit','lCMPLineEdit','lRAYLineEdit','lPAPLineEdit','lBRMLineEdit','iECASCLineEdit']
default_0_values=[2,100,5,1,0,1.0,1.5,2.0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
class Window(QtWidgets.QMainWindow):
def __init__(self):
super(Window,self).__init__()
uic.loadUi('main.ui',self)
self.pushButton_2.clicked.connect(self.reset)
def reset(self):
for le, val in zip(variables, default_0_values):
getattr(self, le).setText(str(val))
if __name__=='__main__':
import sys
app=QtWidgets.QApplication(sys.argv)
window=Window()
window.show()
sys.exit(app.exec())