pyqt5右键菜单

pyqt5右键菜单有两个策略。

from PyQt5.Qt import *



class MyWindow(QWidget):
#自定义窗体
    def contextMenuEvent(self, evt:QContextMenuEvent) -> None:
        print('hello right menu')
        menu=QMenu(self)

        new_action=QAction('打开',menu)
        close_action=QAction('关闭',menu)

        menu.addAction(new_action)
        menu.addAction(close_action)


        #point 调用
        menu.exec_(evt.globalPos())


if __name__=='__main__':
    import sys
    app=QApplication(sys.argv)

    win=MyWindow()
    win.setGeometry(300,300,500,400)

    win.show()

    sys.exit(app.exec_())

第二种策略:

from PyQt5.Qt import *


class MyWindow(QWidget):
    def contextMenuEvent(self, evt:QContextMenuEvent) -> None:
        print('hello right menu')
        menu=QMenu(self)

        new_action=QAction('打开',menu)
        close_action=QAction('关闭',menu)

        menu.addAction(new_action)
        menu.addAction(close_action)


        #point 调用
        menu.exec_(evt.globalPos())






if __name__=='__main__':
    import sys
    app=QApplication(sys.argv)

    win=QWidget()
    win.setGeometry(300,300,500,400)

    def show_menu(point):
        menu=QMenu(win)#将菜单绑定到窗体上

        new_action=QAction('打开',menu)
        close_action=QAction('关闭',menu)

        menu.addAction(new_action)
        menu.addAction(close_action)

        #point 调用
        desk_point=win.mapToGlobal(point) #局部坐标映射到桌面坐标
        #print(point)
        # print(desk_point)
        menu.exec_(desk_point)



    win.setContextMenuPolicy(Qt.CustomContextMenu)#定义右键策略
    win.customContextMenuRequested.connect(show_menu)#发射信号,会传递point





    win.show()

    sys.exit(app.exec_())

你可能感兴趣的:(python,pyqt)