【问题标题】:Python: how to update several variables/fields dynamically [duplicate]Python:如何动态更新多个变量/字段[重复]
【发布时间】: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 的动态列表,而不是您最初开始使用的静态列表

标签: python for-loop pyqt5


【解决方案1】:

类似这样的:

x = ['abc', 'def', 'ghi', 'jkl', 'etc']

for i in range(100):
    xDelta = x[i]

    for widget in centralwidget.children():
        if isinstance(widget, QLineEdit): widget.setText(xDelta)

【讨论】:

  • @juliosouto,成功了吗?
【解决方案2】:

试试看:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from random import randint

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        centralWidget   = QWidget()
        self.setCentralWidget(centralWidget)

        timer = QtCore.QTimer(self, interval=1000)
        timer.timeout.connect(self.updateLineEdit)

        button = QPushButton("Start Update")
        button.clicked.connect(timer.start)

        layout = QVBoxLayout(centralWidget)
        layout.addWidget(button)

        self.x = ['abc', 'def', 'ghi', 'jkl', 'etc', '+== abc', '+== def', '+== ghi', '+== jkl', '+== etc']
        self.listLineEdit = []
        n = len(self.x)

        for i in range(n):
            lineEdit = QLineEdit()
            self.listLineEdit.append(lineEdit)
            layout.addWidget(lineEdit)

    def updateLineEdit(self):
        i = randint(0, 9)
        j = randint(0, 9)
        self.listLineEdit[i].setText(self.x[j])

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

【讨论】:

    猜你喜欢
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多