如何在QTableWidget中显示字典列表中的值?

问题描述 投票:0回答:2

大家好时光。我正在尝试使用词典列表中的值填充QTableWidget。但是在表格中只显示了上一本字典中的值。看起来像以前的值在每个循环上重写。怎么做对了?请帮忙!

spisok = [{'some': 'any 1',
          'some2': 'any 2',
          'some3': 'any 3'},
          {'some': 'any 1a',
           'some2': 'any 2a',
           'some3': 'any 3a'},
          {'some': 'any 1b',
           'some2': 'any 2b',
           'some3': 'any 3b'}
          ]        

for item_list in spisok:
    for col, key in enumerate(item_list):
        for row, value in enumerate(item_list):
            newitem = QTableWidgetItem(value)
            table.setItem(row, col, newitem)
python-3.x pyqt pyqt5
2个回答
0
投票
    row_count = (len(spisok))
    column_count = (len(spisok[0]))

    table.setColumnCount(column_count) 
    table.setRowCount(row_count)

    table.setHorizontalHeaderLabels((list(spisok[0].keys())))

    for row in range(row_count):  # add items from array to QTableWidget
        for column in range(column_count):
            item = (list(spisok[row].values())[column])
            table.setItem(row, column, QTableWidgetItem(item))

结果:

enter image description here

例:

spisok = [{'some': 'any 1',
           'some2': 'any 2',
           'some3': 'any 3'},
          {'some': 'any 1a',
           'some2': 'any 2a',
           'some3': 'any 3a'},
          {'some': 'any 1b',
           'some2': 'any 2b',
           'some3': 'any 3b'},
          {'some': 'any 1c',
           'some2': 'any 2c',
           'some3': 'any 3c'},
          {'some': 'any 1d',
           'some2': 'any 2d',
           'some3': 'any 3d'}
          ]

结果:

enter image description here


0
投票

试试吧:

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

class TableWidget(QWidget): 
    def __init__(self):
        super().__init__()

        spisok = [{'some': 'any 1',  'some2': 'any 2',  'some3': 'any 3'},
                  {'some': 'any 1a', 'some2': 'any 2a', 'some3': 'any 3a'},
                  {'some': 'any 1b', 'some2': 'any 2b', 'some3': 'any 3b'}
                 ]   

        table = QTableWidget()
        table.setRowCount(3)
        table.setColumnCount(3)

        vbox = QVBoxLayout(self)
        vbox.addWidget(table)

        for row, item_list in enumerate(spisok):
            for col, key in enumerate(item_list):
                newitem = QTableWidgetItem(item_list[key])
                table.setItem(row, col, newitem)


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    w = TableWidget()
    w.show()
    sys.exit(app.exec_())

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.