Python:如何动态更新几个变量/字段

时间:2019-10-07 13:16:29

标签: python for-loop pyqt5

我在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]

谢谢

2 个答案:

答案 0 :(得分:0)

类似这样的东西:

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)

答案 1 :(得分:0)

尝试一下:

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_())

enter image description here