from PyQt5.QtWidgets import QApplication, QMenu, QTableWidget, QTableWidgetItem, QWidget, QVBoxLayout, QHBoxLayout
from PyQt5.QtCore import Qt
class TableWidget(QTableWidget):
def __init__(self, rows, columns):
super().__init__(rows, columns)
# 设置表头
self.setHorizontalHeaderLabels(['Column 1', 'Column 2'])
# 添加数据
for i in range(rows):
for j in range(columns):
item = QTableWidgetItem(f'Item {i},{j}')
self.setItem(i, j, item)
# 设置右键菜单
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.show_context_menu)
def show_context_menu(self, pos):
menu = QMenu()
# 获取当前单元格
item = self.itemAt(pos)
if item is None:
return
# 添加操作
edit_action = menu.addAction('Edit')
delete_action = menu.addAction('Delete')
# 执行操作
action = menu.exec_(self.viewport().mapToGlobal(pos))
if action == edit_action:
print(f'Edit {item.text()}')
elif action == delete_action:
self.removeCellWidget(item.row(), item.column())
print(f'Delete {item.text()}')
if __name__ == '__main__':
app = QApplication([])
widget = QWidget()
vbox = QVBoxLayout(widget)
table = TableWidget(5, 2)
vbox.addWidget(table)
widget.setFixedSize(600, 600)
widget.setWindowTitle('Table Widget')
widget.setLayout(vbox)
widget.show()
app.exec_()