Answer the question
In order to leave comments, you need to log in
How to populate a table in PyQt5? Why doesn't it work like this?
There is a list:
data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
-1, -1, -1, -1,
1, 1, 1, 1,
-1, -1, 1, 1,
-1, -1, 1, 1
]
table = QTableWidget()
table.setColumnCount(1)
for i,entry in enumerate(data):
table.setRowCount(i)
entry = str(entry)
item = QTableWidgetItem(entry)
table.setItem(0, i, item)
Answer the question
In order to leave comments, you need to log in
Super simple: the line table.setRowCount(i) means literally: set the number of rows. Guess what next?
If you still haven't guessed:
If you specify print(i) in the loop, it will become clear why it doesn't work.
Still no? enumerate starts iterations from scratch. those. in the first iteration it will turn out like this: "set the number of lines equal to zero, and put entry in the first line."
in the second iteration: "set the number of rows to 1, and try to put entry in the second one".
etc.
In short, the answer is to set table.setRowCount(i) instead of table.setRowCount(i +1 )
and if I were you, I would do not:
entry = str(entry)
item = QTableWidgetItem(entry)
but:
item = QTableWidgetItem()
item.setText(str(entry))
Because explicit is better than implicit. Well, it's so small.......................................... ....... w
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question