[Pyqt5.5 for Python3.4.3 学习笔记]-->QTableWidget表格控件的使用方法
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2016-06-06 22:38:12
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
class myDialog(QDialog):
"""docstring for myDialog"""
def __init__(self, arg=None):
super(myDialog, self).__init__(arg)
self.setWindowTitle("first window")
self.resize(500,300);
conLayout = QHBoxLayout()
tableWidget=QTableWidget()
tableWidget.setRowCount(5)
tableWidget.setColumnCount(4)
conLayout.addWidget(tableWidget)
for i in range(5):
for j in range(4):
tableWidget.setItem(i,j, QTableWidgetItem(self.tr(str(i)+str(j))))
self.setLayout(conLayout)
app = QApplication(sys.argv)
dlg = myDialog()
dlg.show()
dlg.exec_()
app.exit()效果图如下:

设置表格头
tableWidget.setHorizontalHeaderLabels(['a','b','a','b']) tableWidget.setVerticalHeaderLabels(['va','vb','vc','vd','ve'])
上面代码要记得放在下面代码之后否则是没有效果的
tableWidget.setRowCount(5) tableWidget.setColumnCount(4)
运行效果如图:

单元格里面还可以放控件如下代码:
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
class myDialog(QDialog):
"""docstring for myDialog"""
def __init__(self, arg=None):
super(myDialog, self).__init__(arg)
self.setWindowTitle("first window")
self.resize(500,300);
conLayout = QHBoxLayout()
tableWidget=QTableWidget()
tableWidget.setRowCount(5)
tableWidget.setColumnCount(4)
tableWidget.setHorizontalHeaderLabels(['a','b','a','b'])
tableWidget.setVerticalHeaderLabels(['va','vb','vc','vd','ve'])
conLayout.addWidget(tableWidget)
for i in range(5):
for j in range(4):
#可以在单元格中加入控件
comBox = QComboBox();
comBox.addItem("Y");
comBox.addItem("N");
tableWidget.setCellWidget(i,j,comBox);
self.setLayout(conLayout)
app = QApplication(sys.argv)
#全局设置QPushButton的背景样式
dlg = myDialog()
dlg.show()
dlg.exec_()
app.exit()运行效果如下:

单元格默认是可以编辑的下面代码可以设置为只读
tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers);
单元格默认是可以选中单个单元格,下面代码可以设置成选中一行
tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows);
隐藏列表头
#隐藏列表头 tableWidget.verticalHeader().setVisible(False); #隐藏行表头 tableWidget.horizontalHeader().setVisible(False);
还可以将行和列的大小设为与内容相匹配
tableWidget.resizeColumnsToContents(); tableWidget.resizeRowsToContents();