我已经组合了一个输入验证函数(目前没有使用try / except块)。
它工作但纠错带来奇怪的行为......即一旦用户纠正了错误,他们必须按两次计算按钮才能正确触发?
def validation(self):
partval = self.partDiaText.text()
partlentext = self.partLenText.text()
matdia = self.matDiaText.text()
if partval.isalpha():
self.error_label.setText("The part diameter must be a number!")
self.partDiaText.setText("")
elif partval == 0:
self.error_label.setText("The part diameter must be greater than zero!")
elif partlentext.isalpha():
self.partLenText.setText("")
self.error_label.setText("The part length must be a number!")
elif partlentext == 0:
self.error_label.setText("The part length must be greater than zero!")
elif matdia.isalpha():
self.matDiaText.setText("")
self.error_label.setText("The material diameter must be a number!")
elif matdia == 0:
self.error_label.setText("The material diameter must be greater than zero!")
else:
self.error_label.clear()
self.pushButton_2.clicked.connect(self.reset_output)
self.pushButton_2.clicked.connect(self.calc_machining)
self.pushButton_2.clicked.connect(self.calc_times)
self.pushButton_2.clicked.connect(self.calc_qtyVar)
self.pushButton_2.clicked.connect(self.work_centre)
self.pushButton_2.clicked.connect(self.material_code)
编辑:即使没有错误,我仍然需要按两次pushbutton_2才能触发clicked.connects。如果我将所有clicked.connects从验证函数中取出并将它们放入主init函数中,它会正确触发,但输入上没有任何变量。
我的猜测是,正如@noidsirius暗示的那样,第一次使用clic时,会执行验证并连接clic-to-slots。第二次确实执行了插槽。
如果这个猜测是正确的,解决方案可能是:
def __init__(self):
self.pushButton_2.clicked.connect(self.validate_and_run_if_ok)
# etc.
def validate_and_run_if_ok(self):
partval = self.partDiaText.text()
partlentext = self.partLenText.text()
matdia = self.matDiaText.text()
if partval.isalpha():
self.error_label.setText("The part diameter must be a number!")
self.partDiaText.setText("")
elif partval == 0:
self.error_label.setText("The part diameter must be greater than zero!")
elif partlentext.isalpha():
self.partLenText.setText("")
self.error_label.setText("The part length must be a number!")
elif partlentext == 0:
self.error_label.setText("The part length must be greater than zero!")
elif matdia.isalpha():
self.matDiaText.setText("")
self.error_label.setText("The material diameter must be a number!")
elif matdia == 0:
self.error_label.setText("The material diameter must be greater than zero!")
else:
self.error_label.clear()
self.reset_output()
self.calc_machining()
self.calc_times()
self.calc_qtyVar()
self.work_centre()
self.material_code()
(唯一的修改是else块,以及init的附加行)