网站换空间会影响排名吗,网站信息可以,安卓app下载,wordpress terms示例一
我们可以创建一个简单的窗口#xff0c;然后在窗口中添加一个自定义按钮。 当鼠标右键点击按钮时#xff0c;弹出菜单#xff0c;并在菜单中选中某个选项后弹出消息框。
完整代码如下所示#xff1a;
# 导入PyQt库
from PyQt5.QtWidgets import QApplication, QM…示例一
我们可以创建一个简单的窗口然后在窗口中添加一个自定义按钮。 当鼠标右键点击按钮时弹出菜单并在菜单中选中某个选项后弹出消息框。
完整代码如下所示
# 导入PyQt库
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QAction
from PyQt5.QtCore import QPoint# 自定义按钮
class MyButton(QMainWindow):def __init__(self):super().__init__()# 设置按钮self.btn QPushButton(自定义按钮,self)self.btn.resize(100,50)self.btn.move(50,50)# 连接右键菜单self.btn.setContextMenuPolicy(Qt.CustomContextMenu)self.btn.customContextMenuRequested.connect(self.showContextMenu)# 创建右键菜单def showContextMenu(self, pos):menu QMenu(self)menu.addAction(QAction(选项1, self))menu.addAction(QAction(选项2, self))# 菜单事件处理action menu.exec_(self.btn.mapToGlobal(pos))if action:QMessageBox.information(self, 菜单, 你选择了{}.format(action.text()))if __name__ __main__:# 创建应用程序app QApplication(sys.argv)# 创建主窗口mainWindow QMainWindow()btn MyButton()# 设置窗口标题mainWindow.setWindowTitle(程序主窗口)# 显示窗口mainWindow.show()sys.exit(app.exec_())示例二
我们可以在窗口中添加多个自定义按钮每个按钮都有自己的右键菜单并在选中菜单选项后弹出消息框。
完整代码如下所示
# 导入PyQt库
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QAction
from PyQt5.QtCore import QPoint# 自定义按钮
class MyButton(QMainWindow):def __init__(self, text, x, y):super().__init__()# 设置按钮self.btn QPushButton(text, self)self.btn.resize(100,50)self.btn.move(x,y)# 连接右键菜单self.btn.setContextMenuPolicy(Qt.CustomContextMenu)self.btn.customContextMenuRequested.connect(self.showContextMenu)# 创建右键菜单def showContextMenu(self, pos):menu QMenu(self)menu.addAction(QAction(选项1, self))menu.addAction(QAction(选项2, self))# 菜单事件处理action menu.exec_(self.btn.mapToGlobal(pos))if action:QMessageBox.information(self, 菜单, 你选择了{}.format(action.text()))if __name__ __main__:# 创建应用程序app QApplication(sys.argv)# 创建主窗口mainWindow QMainWindow()# 创建自定义按钮btn1 MyButton(按钮1, 50, 50)btn2 MyButton(按钮2, 200, 50)btn3 MyButton(按钮3, 50, 150)btn4 MyButton(按钮4, 200, 150)# 设置窗口标题mainWindow.setWindowTitle(程序主窗口)# 显示窗口mainWindow.show()sys.exit(app.exec_())以上就是Python之PyQt按钮右键菜单功能的实现代码