from __future__ import annotations
import sys
from datetime import datetime
from PySide6.QtGui import QAction, QContextMenuEvent
from PySide6.QtWidgets import QApplication, QMainWindow, QMenu
class MyMainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("ContextMenu Demo")
self.action_button_1 = QAction("按钮1", self)
self.action_button_2 = QAction("按钮2", self)
self.action_button_1.triggered.connect(self.action_button_triggered)
self.action_button_2.triggered.connect(self.action_button_triggered)
def contextMenuEvent(self, event: QContextMenuEvent):
"""
QMainWindow 的 contextMenuEvent(QContextMenuEvent *) 是一个事件处理器
它在用户请求上下文菜单时被触发
默认情况下,这通常发生在用户右键点击窗口的非客户区域(non-client area)时例如标题栏、边框或状态栏
在某些操作系统或窗口管理器中,也可能在点击特定的客户区域(client area)时触发,这取决于系统的行为和用户的设置
contextMenuEvent 事件处理器接收一个 QContextMenuEvent 对象作为参数
该对象包含了触发上下文菜单事件的相关信息,例如位置和原因
"""
context = QMenu()
context.addAction(self.action_button_1)
context.addAction(self.action_button_2)
context.exec(event.globalPos())
print(f'坐标:{event.globalPos().toTuple()},'
f'设备名称:{event.device().name()},'
f'设备类型:{event.deviceType()},'
f'事件类型:{event.type()},'
f'事件来源:{event.reason()}')
def action_button_triggered(self):
action_button = self.sender()
if action_button:
print(action_button.text(), datetime.now().isoformat())
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyMainWindow()
window.show()
sys.exit(app.exec())
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有