本文介绍了Python - PyQt - QTable Widget - 添加行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 PyQt 的新手,无论如何仍然有点困惑.我有一个这样的文本文件结构:

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

  • 姓名 姓氏 电话 电子邮件

现在,当我使用我希望填充 QTable 小部件的方法阅读此文件时,空格实际上是制表符\t".

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

我的 QTable 小部件有 4 列,分别称为 NameSurnameTelephoneEmail 现在它没有行但是当我从文件中读取行并按制表符拆分每一行时,我希望在每列中添加一个新行,该行包含该行中的任何内容.

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.

有人能指出我如何解决这个问题,因为我找不到 QTable Widget 提供的解决方案或方法来让你做到这一点.

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.

推荐答案

当你想填充QTableWidget时,你需要在插入数据之前设置行数和列数文档示例(PySide 文档比 PyQt 好).并且您不能只将由制表符分隔的文本字符串插入表格中,您需要自己准备它,然后通过调用QTableWidget.setItemQTableWidgetItem 填充表格.它看起来像这样:

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)

我假设您有带有条目的 data 文件,并且 tableWidgetQTableWidget 实例.

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

在这个手动解析的示例文件中,但考虑使用标准 csv 模块任务.

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

这篇关于Python - PyQt - QTable Widget - 添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 07:17