文章目录
  1. 1. 源码
  2. 2. 解析
    1. 2.1. 定义窗体
    2. 2.2. 创建托盘

本文主要讲解如何使用 PyQt4 实现一个托盘程序(本程序改写自 Qt4 系统托盘程序)。

源码

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class Widget(QWidget):
def __init__(self, parent = None):
super(Widget, self).__init__(parent)
self.setWindowTitle(self.tr("Tray"))
self.setWindowIcon(QIcon("./img/tray.png"))
trayIcon = QSystemTrayIcon(QIcon("./img/tray.png"), self)
trayIcon.setToolTip(self.tr("this is a pyqt tray test"))
trayIcon.setContextMenu(self.CreateTrayMenu())
trayIcon.setVisible(True)
def CreateTrayMenu(self):
menu = QMenu(self.tr("menu"), self)
minAction = QAction(self.tr("MinSize"), self)
self.connect(minAction, SIGNAL("triggered()"), self.showMinimized)
maxAction = QAction(self.tr("Maxsize"), self)
self.connect(maxAction, SIGNAL("triggered()"), self.showMaximized)
restoreAction = QAction(self.tr("Restore"), self)
self.connect(restoreAction, SIGNAL("triggered()"), self.showNormal)
quitAction = QAction(self.tr("Quit"), self)
self.connect(quitAction, SIGNAL("triggered()"), qApp.quit)
menu.addAction(minAction)
menu.addAction(maxAction)
menu.addAction(restoreAction)
menu.addSeparator()
menu.addAction(quitAction)
return menu
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setQuitOnLastWindowClosed(False)
win = Widget()
win.show()
sys.exit(app.exec_())

解析

定义窗体

首先定义一个 Widget,并继承 QWidget,在构造函数 __init__ 中调用基类 QWidget 的构造函数 super(Widget, self).__init__(parent)。

1
2
3
class Widget(QWidget):
def __init__(self, parent = None):
super(Widget, self).__init__(parent)

并设置窗体标题和窗体图标:

1
2
self.setWindowTitle(self.tr("Tray"))
self.setWindowIcon(QIcon("./img/tray.png"))

创建托盘

创建托盘,并设置工具提示信息,上下文菜单和窗体可视化等属性。

1
2
3
4
5
trayIcon = QSystemTrayIcon(QIcon("./img/tray.png"), self)
trayIcon.setToolTip(self.tr("this is a pyqt tray test"))
trayIcon.setContextMenu(self.CreateTrayMenu())
trayIcon.setVisible(True)

创建托盘菜单并连接相应的响应函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def CreateTrayMenu(self):
# 创建菜单
menu = QMenu(self.tr("menu"), self)
# 窗体最小化
minAction = QAction(self.tr("MinSize"), self)
self.connect(minAction, SIGNAL("triggered()"), self.showMinimized)
# 窗体最大化
maxAction = QAction(self.tr("Maxsize"), self)
self.connect(maxAction, SIGNAL("triggered()"), self.showMaximized)
# 还原
restoreAction = QAction(self.tr("Restore"), self)
self.connect(restoreAction, SIGNAL("triggered()"), self.showNormal)
# 退出
quitAction = QAction(self.tr("Quit"), self)
self.connect(quitAction, SIGNAL("triggered()"), qApp.quit)
# 添加菜单项
menu.addAction(minAction)
menu.addAction(maxAction)
menu.addAction(restoreAction)
menu.addSeparator()
menu.addAction(quitAction)
return menu
文章目录
  1. 1. 源码
  2. 2. 解析
    1. 2.1. 定义窗体
    2. 2.2. 创建托盘