PyQt5 QTableWidget右键表头可以弹出菜单
时间: 2024-05-03 13:21:11 浏览: 268
右键弹出菜单
可以通过继承QTableWidget类并重写mousePressEvent方法来实现右键菜单的弹出。
首先,创建一个新类并继承QTableWidget:
```python
class MyTableWidget(QTableWidget):
def __init__(self, parent=None):
super().__init__(parent)
```
然后,重写mousePressEvent方法:
```python
class MyTableWidget(QTableWidget):
def __init__(self, parent=None):
super().__init__(parent)
def mousePressEvent(self, event):
if event.button() == Qt.RightButton:
pos = event.pos()
if self.horizontalHeader().rect().contains(pos):
menu = QMenu(self)
menu.addAction("Action 1")
menu.addAction("Action 2")
menu.exec_(self.horizontalHeader().mapToGlobal(pos))
```
在mousePressEvent方法中,我们首先检查鼠标按下的是右键,然后检查鼠标的位置是否在水平表头内。如果是,我们创建一个QMenu并添加一些动作,然后在鼠标位置处显示菜单。
最后,我们需要将表格部件设置为我们新创建的表格类:
```python
table = MyTableWidget()
```
完整的示例代码:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, QMenu
from PyQt5.QtCore import Qt
class MyTableWidget(QTableWidget):
def __init__(self, parent=None):
super().__init__(parent)
def mousePressEvent(self, event):
if event.button() == Qt.RightButton:
pos = event.pos()
if self.horizontalHeader().rect().contains(pos):
menu = QMenu(self)
menu.addAction("Action 1")
menu.addAction("Action 2")
menu.exec_(self.horizontalHeader().mapToGlobal(pos))
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
table = MyTableWidget()
table.setRowCount(4)
table.setColumnCount(3)
self.setCentralWidget(table)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
```
阅读全文