U
U
Ulyana Illiterate2016-12-09 12:52:21
Python
Ulyana Illiterate, 2016-12-09 12:52:21

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
                    ]

you need to make a simple label index: value
tried to make
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)

For some reason, it is not filled in, I can not understand why?
if instead of i put the line number, it is written where necessary
2a46ce09b5524fa7a860a24d5fa3350b.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey6661313, 2016-12-09
@karulyana

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 question

Ask a Question

731 491 924 answers to any question