首页 > 其他分享> > PyQt5基础学习-QMenu(右键菜单) 1.QTableWidget().selectionModel().selection().indexes(获得右键选择的索引值) 2.QTableWidg
PyQt5基础学习-QMenu(右键菜单) 1.QTableWidget().selectionModel().selection().indexes(获得右键选择的索引值) 2.QTableWidg
作者:互联网
右键点击表格的选项,然后弹出响应的菜单
TableWidgetContextMenu.py
""" 在表格中显示上下文菜单 1.如何弹出菜单 2.在满足条件下弹出菜单 QMenu.exec_ """ import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * class TableWidgetContextMenu(QWidget): def __init__(self): super(TableWidgetContextMenu, self).__init__() self.initUI() def initUI(self): self.setWindowTitle("在表格中显示上下文菜单") self.resize(500, 300) layout = QHBoxLayout() self.tableWidget = QTableWidget() self.tableWidget.setRowCount(5) self.tableWidget.setColumnCount(3) layout.addWidget(self.tableWidget) self.tableWidget.setHorizontalHeaderLabels(['姓名', '性别', '身高']) newItem = QTableWidgetItem('张三') self.tableWidget.setItem(0, 0, newItem) newItem = QTableWidgetItem('男') self.tableWidget.setItem(0, 1, newItem) newItem = QTableWidgetItem('160') self.tableWidget.setItem(0, 2, newItem) newItem = QTableWidgetItem('李四') self.tableWidget.setItem(1, 0, newItem) newItem = QTableWidgetItem('女') self.tableWidget.setItem(1, 1, newItem) newItem = QTableWidgetItem('170') self.tableWidget.setItem(1, 2, newItem) newItem = QTableWidgetItem('李') self.tableWidget.setItem(2, 0, newItem) newItem = QTableWidgetItem('女') self.tableWidget.setItem(2, 1, newItem) newItem = QTableWidgetItem('170') self.tableWidget.setItem(2, 2, newItem) #允许单机右键响应 self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu) #构建右键的点击事件 self.tableWidget.customContextMenuRequested.connect(self.generateMenu) self.setLayout(layout) def generateMenu(self, pos): print(pos) #获得右键所点击的索引值 for i in self.tableWidget.selectionModel().selection().indexes(): #获得当前的行数目 rowIndex = i.row() #如果选择的索引小于2, 弹出上下文菜单 if rowIndex < 2: #构造菜单 menu = QMenu() #添加菜单的选项 item1 = menu.addAction("菜单项1") item2 = menu.addAction("菜单项2") item3 = menu.addAction("菜单项3") #获得相对屏幕的位置 screenPos = self.tableWidget.mapToGlobal(pos) #被阻塞, 执行菜单 action = menu.exec(screenPos) if action == item1: print("选择了第一个菜单项", self.tableWidget.item(rowIndex, 0).text(), self.tableWidget.item(rowIndex, 1).text(), self.tableWidget.item(rowIndex, 2).text()) elif action == item2: print("选择了第二个菜单项", self.tableWidget.item(rowIndex, 0).text(), self.tableWidget.item(rowIndex, 1).text(), self.tableWidget.item(rowIndex, 2).text()) elif action == item3: print("选择了第三个菜单项", self.tableWidget.item(rowIndex, 0).text(), self.tableWidget.item(rowIndex, 1).text(), self.tableWidget.item(rowIndex, 2).text()) else: return if __name__ == "__main__": app = QApplication(sys.argv) main = TableWidgetContextMenu() main.show() sys.exit(app.exec_())
标签:selection,rowIndex,text,self,QTableWidget,item,tableWidget,右键,newItem 来源: https://www.cnblogs.com/hyq-lst/p/15864054.html