import os import sys from PyQt5 import QtWidgets from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import ( QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QCheckBox, QSystemTrayIcon, QFormLayout, QSpacerItem, QSizePolicy, QMenu, QAction, QStyle, QDialog, QPushButton, QMessageBox) class MessageBox(QMessageBox): def __init__(self): super(MessageBox, self).__init__() save_config = QCheckBox('记住选择') self.layout().addWidget(save_config) class SystemTray(QWidget): def __init__(self): super(SystemTray, self).__init__() self.resize(500, 400) # layout = QFormLayout() # # self.setLayout(layout) # # label = QLabel('最小化到系统托盘?') # layout.addRow(label) # Init QSystemTrayIcon self.tray_icon = QSystemTrayIcon(self) self.tray_icon.setIcon(QIcon(os.getcwd() + '/../images/todo_info.svg')) # # self.style().standardIcon(QStyle.SP_ComputerIcon)) # # self.checkbox = QCheckBox('最小化') # layout.addWidget(self.checkbox) ''' Define and add steps to work with the system tray icon show - show window hide - hide window exit - exit from application ''' show_action = QAction("显示", self) quit_action = QAction("退出", self) hide_action = QAction("隐藏", self) show_action.triggered.connect(self.show) hide_action.triggered.connect(self.hide) quit_action.triggered.connect(QApplication.instance().quit) tray_menu = QMenu() tray_menu.addAction(show_action) tray_menu.addAction(hide_action) tray_menu.addAction(quit_action) self.tray_icon.setContextMenu(tray_menu) self.tray_icon.show() # self.exit_widget = QWidget(self) # # self.exit_widget.setLayout(layout) # 关闭窗口时弹出确认消息 def closeEvent(self, event): # 创建一个消息盒子(提示框) quitMsgBox = QMessageBox() quitMsgBox.resize(300, 200) # 设置提示框的标题 quitMsgBox.setWindowTitle('确认窗口') # 设置提示框的内容 quitMsgBox.setText('你确定退出吗?') # 创建两个点击的按钮,修改文本显示内容 buttonY = QPushButton('退出程序') buttonN = QPushButton('最小化到托盘') # 将两个按钮加到这个消息盒子中去,并指定yes和no的功能 style = """ /*设置堆栈按钮样式*/ QPushButton { /* padding: 3px 20px;*/ /* text-align:center;*/ background-color:orange; border-radius:15px; } QPushButton:hover { /* padding: 3px 20px;*/ /* text-align:center;*/ background-color:#dddddd; border-radius:15px; } QPushButton:pressed { /* padding: 3px 20px;*/ /* text-align:center;*/ background-color:#9f9f9f; border-radius:15px; } """ buttonY.setStyleSheet(style) buttonN.setStyleSheet(style) quitMsgBox.addButton(buttonY, QMessageBox.YesRole) quitMsgBox.addButton(buttonN, QMessageBox.NoRole) quitMsgBox.exec_() # 判断返回值,如果点击的是Yes按钮,我们就关闭组件和应用,否则就忽略关闭事件 if quitMsgBox.clickedButton() == buttonY: event.accept() else: self.hide() event.ignore() # if self.checkbox.isChecked(): # event.ignore() # self.hide() # if self.check_box.isChecked(): # event.ignore() # self.hide() # self.tray_icon.showMessage( # "Tray Program", # "Application was minimized to Tray", # QSystemTrayIcon.Information, # 2000 # ) if __name__ == '__main__': app = QApplication(sys.argv) main = SystemTray() main.show() sys.exit(app.exec_())