import sys
import traceback
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *


class Main(QDialog):
    """弹出菜单Demo"""
    def __init__(self, parent=None):
        try:
            super(Main, self).__init__(parent)
            self.init_ui()
            self.init_slot()
        except:
            traceback.print_exc()

    def init_ui(self):
        try:
            self.resize(320, 320)
            self.setWindowTitle("弹出菜单demo")

            self.label = QLabel(self)
            self.label.setText("弹出菜单demo")

            self.pushButton_1 = QPushButton(self)
            self.pushButton_1.setText("左键菜单")

            self.pushButton_2 = QPushButton(self)
            self.pushButton_2.setText("右键菜单")

            layout = QHBoxLayout()
            layout.addWidget(self.label)
            layout.addWidget(self.pushButton_1)
            layout.addWidget(self.pushButton_2)

            self.setLayout(layout)
        except:
            traceback.print_exc()

    def init_slot(self):
        try:
            self.pushButton_1.clicked.connect(self.left_button_menu)
            self.pushButton_2.setContextMenuPolicy(Qt.CustomContextMenu)  # 右键菜单
            self.pushButton_2.customContextMenuRequested.connect(self.right_button_menu)
        except:
            traceback.print_exc()

    def left_button_menu(self):
        try:
            # 创建菜单
            menu = QMenu(self)
            # 定义菜单选项
            action1 = menu.addAction("透明度0.2")
            action2 = menu.addAction("透明度0.6")
            action3 = menu.addAction("透明度1.0")

            # 菜单绑定事件
            action1.triggered.connect(lambda: self.setWindowOpacity(0.2))
            action2.triggered.connect(lambda: self.setWindowOpacity(0.6))
            action3.triggered.connect(lambda: self.setWindowOpacity(1.0))

            menu.exec_(QCursor.pos())
        except:
            traceback.print_exc()

    def right_button_menu(self):
        try:
            # 创建菜单
            menu = QMenu(self)
            # 定义菜单选项
            action1 = menu.addAction("最小化")
            action2 = menu.addAction("最大化")
            action3 = menu.addAction("正常")

            # 菜单绑定事件
            action1.triggered.connect(self.showMinimized)
            action2.triggered.connect(self.showMaximized)
            action3.triggered.connect(self.showNormal)

            menu.exec_(QCursor.pos())
        except:
            traceback.print_exc()



if __name__ == '__main__':
    authorization = None
    app = QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec_())
