我试图用pyQt5将数据填充到我的Qtablewdiget中。除此之外,我想在表的特定列上添加一个上下文菜单。我已经实现了在整个表上弹出Qmenu,但有人能帮助我如何实现特定列的上下文菜单操作吗。
查看我进一步工作的快照,我尝试了
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QPushButton, QAction, QApplication, QLabel, QMainWindow, QMenu)
from PyQt5 import QtCore, QtGui, QtWidgets
# setting context menu policy on my table, "self.ui.tableWidgetGraph"
self.ui.tableWidgetGraph.setContextMenuPolicy(Qt.CustomContextMenu)
# setting context menu request by calling a function,"self.on_context_menu"
self.ui.tableWidgetGraph.customContextMenuRequested.connect(self.on_context_menu)
# define table size
self.ui.tableWidgetGraph.setRowCount(length);
self.ui.tableWidgetGraph.setColumnCount(lenColumn);
def on_context_menu(self, point):
# show context menu
self.contextMenu = QMenu(self)
Task_one_action = self.contextMenu.addAction("Task_one")
self.contextMenu.addSeparator()
Task_two_action = self.contextMenu.addAction("Task_two")
self.contextMenu.addSeparator()
quit_action = self.contextMenu.addAction("Quit")
# I want to perform actions only for a single column(E.g: Context menu only for column 4 of my table
# Need help here....???
action = self.contextMenu.exec_(self.ui.tableWidgetGraph.mapToGlobal(point))
self.selected_key = ""
for self.item in self.ui.tableWidgetGraph.selectedItems():
self.selected_key = self.item.text()
if action == quit_action:
print("Executing the [Quit/Exit] Action")
qApp.quit()
elif action == Task_one_action:
print("Executing Search: [Task_one_action ]")
elif action == Task_two_action:
print("Executing Search: [Task_two_action ]")
有人能指导我如何只对一列执行上下文操作吗(例如:上下文菜单只针对我表第4列中的选定项目(,。感谢
您可以使用itemAt在某个位置获取项,然后使用column()
,但由于它可能是一个空项,因此无论该列是否存在,它都会返回None。
使用indexAt()
(它由QTableView继承,QTableWidget就是基于它构建的(来获得模型索引:
def on_context_menu(self, pos):
index = self.ui.tableWidgetGraph.indexAt(pos)
if index.isValid() and index.column() == 3:
menu = QtWidgets.QMenu()
menu.addAction('Action for column 4')
menu.exec_(self.ui.tableWidgetGraph.viewport().mapToGlobal(pos))
index.isValid()
是检查索引是否确实存在于这些坐标处:例如,如果您在第四列的垂直范围内单击,但在这些坐标处尚未设置行,则会得到一个无效的索引(没有任何行或列(。
这显然意味着,如果您需要获得该列的菜单,无论此时是否存在行,上述方法都不起作用
如果是这样的话,您需要对照表头进行检查:
def on_context_menu(self, pos):
index = self.ui.tableWidgetGraph.indexAt(pos)
validColumn = index.isValid() and index.column() == 3
if not validColumn:
left = self.ui.tableWidgetGraph.horizontalHeader().sectionPosition(3)
width = self.ui.tableWidgetGraph.horizontalHeader().sectionSize(3)
if left <= pos.x() <= left + width:
validColumn = True
if validColumn:
menu = QtWidgets.QMenu()
menu.addAction('Action for column 4')
menu.exec_(self.ui.tableWidgetGraph.viewport().mapToGlobal(pos))