12.12 PyQt5-QTableWidget应用案例【单元格添加控件】
1.单元格添加控件方式
QTableWidget的setCellWidget方法为指定单元格添加控件,例如:按钮、下拉框等,并将控件连接指定信号,实现更复杂的表格操作。
2.单元格添加控件案例
import sys
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QHBoxLayout, QWidget, QPushButton, QComboBox
class QTableWidgetAddWidgetDemo(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.setWindowTitle('QTableWidget添加控件演示')
self.resize(600, 400)
h_layout = QHBoxLayout(self)
table = QTableWidget()
self.table = table
table.setRowCount(4)
table.setColumnCount(4)
table.setHorizontalHeaderLabels(['姓名', '性别', '操作', '删除'])
table.setItem(0, 0, QTableWidgetItem('张三'))
com_box = QComboBox() # 设置下拉框
self.com_box = com_box
com_box.addItem('男')
com_box.addItem('女')
com_box.setStyleSheet('QComboBox{margin: 3px};') # 设置qss样式
table.setCellWidget(0, 1, com_box) # 通过setCellWidget来为单元格添加控件,参数:(第几行, 第几列, 控件实例)
modify = QPushButton('修改')
modify.setStyleSheet('QPushButton{margin: 3px}')
table.setCellWidget(0, 2, modify)
modify.clicked.connect(self.md)
modify = QPushButton('删除')
modify.setStyleSheet('QPushButton{margin: 3px}')
table.setCellWidget(0, 3, modify)
modify.clicked.connect(self.md)
h_layout.addWidget(table)
def md(self):
print(self.table.item(self.table.currentIndex().row(), 0).text())
print(self.com_box.itemText(self.com_box.currentIndex()))
if __name__ == '__main__':
app = QApplication(sys.argv)
w = QTableWidgetAddWidgetDemo()
w.show()
app.exec()