怎么用QMenu创建按钮上的右键菜单
时间: 2023-09-22 13:05:58 浏览: 42
可以通过QMenu类来创建按钮上的右键菜单,具体步骤如下:
1. 创建QMenu对象:
```python
menu = QMenu(self)
```
2. 创建QAction对象,用于添加到QMenu中:
```python
action1 = QAction("Action 1", self)
action2 = QAction("Action 2", self)
```
3. 将创建的QAction对象添加到QMenu中:
```python
menu.addAction(action1)
menu.addAction(action2)
```
4. 给按钮绑定右键菜单:
```python
button.setContextMenuPolicy(Qt.CustomContextMenu)
button.customContextMenuRequested.connect(menu.show)
```
完整的代码示例:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QMenu, QAction
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Right-click menu example')
button = QPushButton('Right-click me', self)
button.setGeometry(50, 50, 120, 30)
menu = QMenu(self)
action1 = QAction("Action 1", self)
action2 = QAction("Action 2", self)
menu.addAction(action1)
menu.addAction(action2)
button.setContextMenuPolicy(Qt.CustomContextMenu)
button.customContextMenuRequested.connect(menu.show)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)