Pyside2 按钮右击菜单实例


免责声明 本站所提供的部分内容,为作者提供、网友推荐、互联网整理而来,仅供学习参考,如有侵犯您的版权,请联系我们,本站将在三个工作日内删除。
import sys
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
 
class MainForm(QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)
 
        # create button
        self.button = QPushButton("test button", self)       
        self.button.resize(100, 30)
 
        # set button context menu policy
        self.button.setContextMenuPolicy(Qt.CustomContextMenu)
        self.button.customContextMenuRequested.connect(self.on_context_menu)
 
        # create context menu
        self.popMenu = QMenu(self)
        self.popMenu.addAction(QAction('test0', self))
        self.popMenu.addAction(QAction('test1', self))
        self.popMenu.addSeparator()
        self.popMenu.addAction(QAction('test2', self))
 
    def on_context_menu(self, point):
        # show context menu
        self.popMenu.exec_(self.button.mapToGlobal(point))
 
def main():
    app = QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()
 
if __name__ == '__main__':
    main()