凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

7. PyQt6 上下文菜单

2023-10-17 python 313
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QMenu
from PyQt6.QtGui import QGuiApplication


class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("PyQt6 上下文菜单")

        self.setGeometry(100, 100, 400, 300)
        self.center()

    def contextMenuEvent(self, event):
        cmenu = QMenu(self)
        new_act = cmenu.addAction("新建")
        open_act = cmenu.addAction("打开")
        quit_act = cmenu.addAction("退出")

        action = cmenu.exec(self.mapToGlobal(event.pos()))

        if action == quit_act:
            QApplication.instance().quit()

    def center(self):
        qr = self.frameGeometry()
        cp = QGuiApplication.primaryScreen().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    cls_app = App()
    cls_app.show()
    sys.exit(app.exec())

image.png

文章评论

0条评论