QTablewidget生成右键菜单,需要自定义一个QTablewidget类
import sys
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QMenu, QAction, QDialog
from PyQt5.QtCore import Qt
from PyQt5 import QtCore
class CustomTableWidget(QTableWidget):
def __init__(self, parent=None):
super(CustomTableWidget, self).__init__( parent)
self.setRowCount(10)
self.setColumnCount(2)
# 初始化表格数据
self.setHorizontalHeaderLabels(['姓名','班别']) #水平标题
names = ['小天','小米','小云','小月','小芳','小贝','小美','小亮','小欢','小阳']
classes = ['一班','一班','一班','二班','二班','二班','二班','三班','三班','三班']
i = 0
for item in names:
self.setItem(i,0, QTableWidgetItem(item))#添加内容到表格中
self.setItem(i,1, QTableWidgetItem(classes[i]))
i += 1
# 创建右键菜单
self.popup_menu = QMenu(self)
self.action1 = QAction("显示", self)#生成一个选项
self.popup_menu.addAction(self.action1)#将选项添加到菜单中
# 连接动作到槽函数(可选)
self.action1.triggered.connect(self.on_action1_triggered)
def mousePressEvent(self, event):#重写mousePressEvent
if event.button() == Qt.RightButton:
# 获取点击的单元格位置
self.row = self.rowAt(event.y())#行
self.column = self.columnAt(event.x())#列
super().mousePressEvent(event)#调用父类的mousePressEvent处理其他事件
# 显示右键菜单
self.popup_menu.exec_(event.globalPos())
else:
super().mousePressEvent(event)#调用父类的mousePressEvent处理其他事件
def on_action1_triggered(self):
# 菜单选项action1的动作
print(f"行:{self.row} 列:{self.column}")
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = QDialog()
dialog.resize(400, 300)
table = CustomTableWidget(dialog) # 创建一个表格
table.setGeometry(QtCore.QRect(70, 50, 256, 192))
dialog.show()
sys.exit(app.exec_())
按F5运行,在界面的表格中按右键时,显示菜单
选中显示是,控制台输出选中的行数和列数
QAction的信号
信号 | 内容 |
---|---|
triggered | 点击或回车键触发时 |