# coding: utf-8
import sys
import traceback

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore 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.setWindowFlags(Qt.WindowCloseButtonHint | Qt.WindowMinMaxButtonsHint)

            label = QLabel(self)
            # label.setAlignment(Qt.AlignCenter)
            label.setText("系统托盘Demo,最小化隐藏窗口，点击系统托盘恢复窗口")

            layout = QHBoxLayout()
            layout.addWidget(label)
            self.setLayout(layout)

            # 系统托盘
            self.system_tray = QSystemTrayIcon(QIcon(r"C:\Users\xyzou\Pictures\1.png"))
            self.system_tray.setToolTip("这是系统托盘")
            self.system_tray.show()
        except:
            traceback.print_exc()

    def init_slot(self):
        try:

            self.system_tray.activated.connect(self.system_tray_menu)
        except:
            traceback.print_exc()

    def changeEvent(self, event):
        """最小化隐藏"""
        try:
            if event.type() == QEvent.WindowStateChange:
                if self.isMinimized():
                    self.setVisible(False)
        except:
            traceback.print_exc()

    def system_tray_menu(self, reason):
        """系统托盘菜单
        鼠标点击icon传递的信号会带有一个整形的值，1是表示单击右键，2是双击，3是单击左键，4是用鼠标中键点击
        """
        try:
            if reason == 2 or reason == 3:
                # 显示主界面
                self.showNormal()
            elif reason == 1:
                # 创建菜单
                menu = QMenu(self)
                # 定义菜单选项
                action1 = menu.addAction("显示界面")
                action2 = menu.addAction("退出")

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

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

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