在 Python 中使用 PyQt4 向 QTableWidget 添加数据 [英] Adding data to QTableWidget using PyQt4 in Python

查看:34
本文介绍了在 Python 中使用 PyQt4 向 QTableWidget 添加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 python 中使用 pyqt 将我的数据添加到表中.我发现我应该使用 setItem() 函数将数据添加到 QTableWidget 并给它行号和列号以及 QTableWidgetItem.我做到了,但是当我想显示表格时,它完全是空的.也许我犯了一个愚蠢的错误,但请帮助我.这是我的代码:

I want to add my data to a table using pyqt in python. I found that I should use setItem() function to add data to a QTableWidget and give it the row and column number and a QTableWidgetItem. I did it but when I want to display the table, it's completely empty. Maybe I made a silly mistake but please help me. Here is my code:

from PyQt4 import QtGui

class Table(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Table, self).__init__(parent)
        layout = QtGui.QGridLayout() 
        self.led = QtGui.QLineEdit("Sample")
        self.table = QtGui.QTableWidget()
        layout.addWidget(self.led, 0, 0)
        layout.addWidget(self.table, 1, 0)
        self.table.setItem(1, 0, QtGui.QTableWidgetItem(self.led.text()))
        self.setLayout(layout)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    t = Table()
    t.show()
    sys.exit(app.exec_())

推荐答案

您正在寻找的是 setRowCount()setColumnCount() 方法.在 QTableWidget 上调用这些来指定行数/列数.例如

What you are looking for are the setRowCount() and setColumnCount() methods. Call these on the QTableWidget to specify the number of rows/columns. E.g.

...
self.table = QtGui.QTableWidget()
self.table.setRowCount(5)
self.table.setColumnCount(5)
layout.addWidget(self.led, 0, 0)
layout.addWidget(self.table, 1, 0)
self.table.setItem(1, 0, QtGui.QTableWidgetItem(self.led.text()))
...

此代码将创建一个 5x5 表格并在第二行(索引为 1)和第一列(索引为 0)中显示示例".

This code will make a 5x5 table and display "Sample" in the second row (with index 1) and first column (with index 0).

如果不调用这两个方法,QTableWidget 就不会知道表格有多大,因此将 item 设置在位置 (1, 0) 没有意义.

Without calling these two methods, QTableWidget would not know how large the table is, so setting the item at position (1, 0) would not make sense.

如果您不知道,Qt 文档 很详细,包含许多示例(可以很容易转换为 Python).详细说明"部分特别有用.如果您想了解有关 QTableWidget 的更多信息,请访问:http://qt-project.org/doc/qt-4.8/qtablewidget.html#details

In case you are unaware of it, the Qt Documentation is detailed and contains many examples (which can easily be converted to Python). The "Detailed Description" sections are especially helpful. If you want more information about QTableWidget, go here: http://qt-project.org/doc/qt-4.8/qtablewidget.html#details

这篇关于在 Python 中使用 PyQt4 向 QTableWidget 添加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆