【发布时间】:2019-10-07 21:59:31
【问题描述】:
我在 PyQT5 中有几个字段(不时更改),我想在 for 循环中动态更新它们。有没有一种方法可以做到这一点,而不必像我为 xDelta 变量那样逐个字段输入?
以下示例:
x = ['abc', 'def', 'ghi', 'jkl', 'etc']
for i in range(100):
xDelta = x[i]
**# I want the rows below to be one row only, updating the "lineEdit_X" dynamically:**
self.lineEdit_20.setText(xDelta) # instead of x[20]
self.lineEdit_21.setText(xDelta) # instead of x[21]
self.lineEdit_22.setText(xDelta) # instead of x[22]
self.lineEdit_23.setText(xDelta) # instead of x[23]
self.lineEdit_24.setText(xDelta) # instead of x[24]
谢谢
【问题讨论】:
-
检查
setattr(my_obj, attr_name, 'my_value') -
这里你甚至不需要
setattr;考虑y = self.lineEdit_20; y.setText(xDelta)。 -
奇怪的是(除非我错过了)没有人建议处理这个问题的最 Pythonic 版本,那就是将每个 LineEdits 放在一个 List 中,然后总是通过下标访问它们,因为创建self.LineEdit_# 根本不是要走的路,而是 List[#] = QLineEdit('Base Name') 这样您就可以拥有 QLineEdits 的动态列表,而不是您最初开始使用的静态列表