pyqt5的Qmenu如何与函数连接
时间: 2023-12-25 16:06:14 浏览: 30
要将 PyQt5 中的 QMenu 与函数连接,可以使用 QAction 对象。QAction 对象包括一个名称和一个可选的图标,还可以与槽函数或 lambda 表达式连接。以下是一个示例代码,演示如何将 QMenu 与函数连接:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QAction
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
menubar = self.menuBar()
fileMenu = menubar.addMenu('File')
# 创建一个 QAction 对象并将其连接到槽函数
openFile = QAction('Open', self)
openFile.triggered.connect(self.open_file)
# 将 QAction 添加到 QMenu 中
fileMenu.addAction(openFile)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('QMenu Example')
self.show()
def open_file(self):
print('Open file')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainWindow()
sys.exit(app.exec_())
```
在上面的示例中,我们创建了一个名为 `openFile` 的 QAction 对象,并将其连接到 `open_file()` 函数。然后,我们将 `openFile` 添加到 `fileMenu` 中。当用户单击“Open”菜单项时,将触发 `open_file()` 函数,并打印一条消息。
这是一个简单的示例,可以根据需要进行修改。