PyQT开发图形界面应用时,用 QTableWidget 表格控件可用表格方式显示从列表、数据库, excel 等读出的二维数据。
如果你想用表格方式显示自已建立的 Model 模型数据,请采用QTableView类。
步骤如下:
示例中,生成1个联系人表格,
创建1个QTableWidget对象
# 创建 QTablewWidget对象,设置表头及参数
self.table = QTableWidget(4,3,self)
self.table.setHorizontalHeaderLabels(['姓名','邮件','电话'])
self.table = QTableWidget(4,3,self)
创建QTableWidget对象,尺寸为 4行 * 3列
也可以这样设置
table.setRowCount(4)
table.setColumnCount(3)
self.table.setHorizontalHeaderLabels(['姓名','邮件','电话'])
设置表头
self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
由于第2列可能比较宽,设置第2列伸展
有的字段比较长,可以设置按内容设置列宽,按内容设置行高。
self.table.resizeColumnsToContents()
self.table.resizeRowsToContents()
self.table.setShowGrid(True)
显示网格线
self.table.setItem(0,0, QTableWidgetItem("张飞"))
self.table.setItem(0,1, QTableWidgetItem("[email protected]"))
self.table.setItem(0,2, QTableWidgetItem("021-3233288"))
表格项对应类为QTableWidgetItem,
QTableWidgetItem(“张飞”)
添加到表格中
self.table.setItem(0,2, QTableWidgetItem("021-3233288"))
表示,将指定表格项添加到第1行,第3列单元格。
默认int, float 型数值必须转换为字符串类型,才能显示。 表格项直接使用int型,采用下面方法
item = QTableWidgetItem()
item.setData(Qt.EditRole,55555555)
self.table.setItem(3, 2, item)
我们采用了自定义的方式添加行
def addTableRow(self, table, row_data):
# 功能: 在末尾添加新行
row = table.rowCount()
table.setRowCount(row+1)
col = 0
for item in row_data:
cell = QTableWidgetItem(str(item))
table.setItem(row, col, cell)
col += 1
print(f"Added one row: {row_data}")
print(f"totally, {row+1} rows")
删除行:
removeRow(10) , 即删除第11行
QTableWidgets 提供如下信号
def cellActivated (row, column)
def cellChanged (row, column)
def cellClicked (row, column)
def cellDoubleClicked (row, column)
def cellEntered (row, column)
def cellPressed (row, column)
def currentCellChanged (currentRow, currentColumn, previousRow, previousColumn)
def currentItemChanged (current, previous)
def itemActivated (item)
def itemChanged (item)
def itemClicked (item)
def itemDoubleClicked (item)
def itemEntered (item)
def itemPressed (item)
def itemSelectionChanged ()
内置Slot方法
def clear ()
def clearContents ()
def insertColumn (column)
def insertRow (row)
def removeColumn (column)
def removeRow (row)
def scrollToItem (item[, hint=EnsureVisible])
例,绑定单元格双击信号至slot方法 table_double_clicked
self.table.cellDoubleClicked.connect(self.table_double_clicked)
当然,你也可以自定义信号类型。
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class MyWin(QWidget):
def __init__(self):
super().__init__()
self.title = "PyQt5 TableWidget"
self.top = 100
self.left = 100
self.width = 600
self.height = 380
self.InitWindow()
def InitWindow(self):
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.creatingTables()
self.vBoxLayout = QVBoxLayout()
self.vBoxLayout.addWidget(self.table)
self.setLayout(self.vBoxLayout)
self.show()
def creatingTables(self):
# 创建 QTablewWidget对象,设置表头及参数
self.table = QTableWidget(4,3,self)
self.table.setShowGrid(True)
self.table.setHorizontalHeaderLabels(('姓名','邮件','电话' ))
self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
# 表格内容
self.table.setItem(0,0, QTableWidgetItem("张飞"))
self.table.setItem(0,1, QTableWidgetItem("[email protected]"))
self.table.setItem(0,2, QTableWidgetItem("021-3233288"))
self.table.setItem(1,0, QTableWidgetItem("李军"))
self.table.setItem(1,1, QTableWidgetItem("[email protected]"))
self.table.setItem(1,2, QTableWidgetItem("021-34334433"))
self.table.setItem(2, 0, QTableWidgetItem("王小乙"))
self.table.setItem(2, 1, QTableWidgetItem("[email protected]"))
self.table.setItem(2, 2, QTableWidgetItem("2232324"))
self.table.setItem(3, 0, QTableWidgetItem("赵无忌"))
self.table.setItem(3, 1, QTableWidgetItem("[email protected]"))
item = QTableWidgetItem()
item.setData(Qt.EditRole,55555555)
self.table.setItem(3, 2, item)
# 添加1条新记录
row_5 = ['钱晓芬',"[email protected]","12343445" ]
row_6 = ['孙涛','[email protected]','88888888']
self.addTableRow(self.table, row_5)
self.addTableRow(self.table, row_6)
self.table.resizeColumnsToContents()
self.table.resizeRowsToContents()
self.table.cellDoubleClicked.connect(self.table_double_clicked)
def addTableRow(self, table, row_data):
# 功能: 在末尾添加新行
row = table.rowCount()
table.setRowCount(row+1)
col = 0
for item in row_data:
cell = QTableWidgetItem(str(item))
table.setItem(row, col, cell)
col += 1
print(f"Added one row: {row_data}")
print(f"totally, {row+1} rows")
def table_double_clicked(self,row,col):
# 打印选中单元格的内容
print(f" Value of cell ({row},{col}) is {self.table.item(row,col).text()} ")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyWin()
sys.exit(app.exec())
Added one row: ['钱晓芬', '[email protected]', '12343445']
totally, 5 rows
Added one row: ['孙涛', '[email protected]', '88888888']
totally, 6 rows
Value of cell (2,2) is 2232324