0

I have a QtWidget, built in QtCreator. Let's say there are 10 QLineEdits in the widget named Edit0 to Edit9. The data that is supposed to go in them is stored in a Python list data. Is there a way to put those 10 QLineEdits in a Python list so I can basically assign their values like:

for index in range(len(data)):
    Edit[index].setText('{:.2}'.format(data[index]))
FR_MPI
  • 111
  • 1
  • 9

1 Answers1

0

Since you're using python, you can access fields via string:

for index in range(len(data)):
    getattr(ui, f"Edit{index}").setText('{:.2}'.format(data[index]))

But relying on the name is an ugly style.

You can also iterate over the layout which contains the edits. Here is how to do it in C++, the method names are the same in python. But that becomes ugly if you want to add something else to the layout, e.g., a Button.

Neither of these methods do scale. If you have many edits in a fixed pattern, you should consider creating them yourself with your code and put them in a list in the first place.

edits = []
for index in range(42):
    edit = QLineEdit()
    edits.append(edit)
    ui.some_layout.addWidget(edit)  # add edit to the layout

# later:   
for edit, data in zip(edits, data):
    edit.setText('{:.2}'.format(data[index]))

However, it seems to me like you're building a table. Do you know QListWidget, QTableWidget, QListView and QTableView?

pasbi
  • 2,037
  • 1
  • 20
  • 32