Python - PyQt - QTable Widget - adding rows

ぐ巨炮叔叔 提交于 2020-01-13 08:21:31

问题


i am new to PyQt and still bit confused anyhow. I have a text file structure like this:

  • Name Surname Telephone Email

Where spaces are actually tabs " \t " now when i read this file whit my method i wish to populate the QTable Widget.

My QTable Widget has 4 columns called Name, Surname, Telephone, Email now it has no rows but as I read lines from the file and split each line by tabulator I wish to add a new row that in each column contains whatever was in the line.

Could someone point me in the direction how to go about this because I cannot find a solution or a method offered by QTable Widget that allows you to this.


回答1:


When you want to populate QTableWidget, you need to set row and column counts before inserting data example in documentation (PySide documentation is better than PyQt). And you can't just insert text string separated by tabs into table, you need to prepare it yourself, and then populate table with QTableWidgetItem's by calling QTableWidget.setItem. It will look like this:

entries = []
with open('data') as input:
    for line in input:
        entries.append(line.strip().split('\t'))

tableWidget.setRowCount(len(entries))
tableWidget.setColumnCount(len(entries[0]))

for i, row in enumerate(entries):
    for j, col in enumerate(row):
        item = QTableWidgetItem(col)
        tableWidget.setItem(i, j, item)

I'm assuming that you have data file with your entries, and tableWidget is QTableWidget instance.

In this example file parsed by hand, but consider using standart csv module for this task.



来源:https://stackoverflow.com/questions/8775447/python-pyqt-qtable-widget-adding-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!