QTableWidget
‘‘‘ 扩展的表格控件(QTableWidget) QTableView 每一个Cell(单元格)是一个QTableWidgetItem ‘‘‘ import sys from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem, QAbstractItemView) class TableWidgetDemo(QWidget): def __init__(self): super(TableWidgetDemo,self).__init__() self.initUI() def initUI(self): self.setWindowTitle("QTableWidget演示") self.resize(430, 230); layout = QHBoxLayout() tablewidget = QTableWidget() tablewidget.setRowCount(4) tablewidget.setColumnCount(3) layout.addWidget(tablewidget) tablewidget.setHorizontalHeaderLabels([‘姓名‘,‘年龄‘,‘籍贯‘]) nameItem = QTableWidgetItem("小明") tablewidget.setItem(0,0,nameItem) ageItem = QTableWidgetItem("24") tablewidget.setItem(0,1,ageItem) jgItem = QTableWidgetItem("北京") tablewidget.setItem(0,2,jgItem) # 禁止编辑 tablewidget.setEditTriggers(QAbstractItemView.NoEditTriggers) # 整行选择 tablewidget.setSelectionBehavior(QAbstractItemView.SelectRows) # 调整列和行 tablewidget.resizeColumnsToContents() tablewidget.resizeRowsToContents() # tablewidget.horizontalHeader().setVisible(False) # tablewidget.verticalHeader().setVisible(False) tablewidget.setVerticalHeaderLabels(["a","b"]) # 隐藏表格线 tablewidget.setShowGrid(False) self.setLayout(layout) if __name__ == ‘__main__‘: app = QApplication(sys.argv) example = TableWidgetDemo() example.show() sys.exit(app.exec_())
QTableView
‘‘‘ 显示二维表数据(QTableView控件) 数据源 Model 需要创建QTableView实例和一个数据源(Model),然后将两者关联 MVC:Model Viewer Controller MVC的目的是将后端的数据和前端页面的耦合度降低 ‘‘‘ from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys class TableView(QWidget): def __init__(self, arg=None): super(TableView, self).__init__(arg) self.setWindowTitle("QTableView表格视图控件演示") self.resize(500,300); self.model = QStandardItemModel(4,3) self.model.setHorizontalHeaderLabels([‘id‘,‘姓名‘,‘年龄‘]) self.tableview = QTableView() # 关联QTableView控件和Model self.tableview.setModel(self.model) # 添加数据 item11 = QStandardItem(‘10‘) item12 = QStandardItem(‘雷神‘) item13 = QStandardItem(‘2000‘) self.model.setItem(0,0,item11) self.model.setItem(0,1, item12) self.model.setItem(0,2, item13) item31 = QStandardItem(‘30‘) item32 = QStandardItem(‘死亡女神‘) item33 = QStandardItem(‘3000‘) self.model.setItem(2,0,item31) self.model.setItem(2,1, item32) self.model.setItem(2,2, item33) layout = QVBoxLayout() layout.addWidget(self.tableview) self.setLayout(layout) if __name__ == ‘__main__‘: app = QApplication(sys.argv) table = TableView() table.show() sys.exit(app.exec_())
原文:https://www.cnblogs.com/wuyuan2011woaini/p/14817246.html