Pyqt QSystemTrayIcon 实现托盘效果

 

    pyqt的托盘效果很好实现,在Pyqt的demo中有个例子

路径:PyQt4\examples\desktop\systray.py

Pyqt QSystemTrayIcon 实现托盘效果

今天我就仿这个Tray效果做效果

一. 创建UI

trayicon.ui文件:

  1 <?xml version="1.0" encoding="UTF-8"?>

  2 <ui version="4.0">

  3  <class>TrayIcon</class>

  4  <widget class="QWidget" name="TrayIcon">

  5   <property name="geometry">

  6    <rect>

  7     <x>0</x>

  8     <y>0</y>

  9     <width>418</width>

 10     <height>441</height>

 11    </rect>

 12   </property>

 13   <property name="maximumSize">

 14    <size>

 15     <width>1024</width>

 16     <height>16777215</height>

 17    </size>

 18   </property>

 19   <property name="windowTitle">

 20    <string>Form</string>

 21   </property>

 22   <layout class="QVBoxLayout" name="verticalLayout">

 23    <item>

 24     <widget class="QGroupBox" name="groupBoxTrayIcon">

 25      <property name="minimumSize">

 26       <size>

 27        <width>400</width>

 28        <height>100</height>

 29       </size>

 30      </property>

 31      <property name="maximumSize">

 32       <size>

 33        <width>16777215</width>

 34        <height>100</height>

 35       </size>

 36      </property>

 37      <property name="title">

 38       <string>托盘图标</string>

 39      </property>

 40      <layout class="QVBoxLayout" name="verticalLayout_2">

 41       <item>

 42        <layout class="QHBoxLayout" name="horizontalLayoutByrayicon">

 43         <item>

 44          <widget class="QLabel" name="label">

 45           <property name="text">

 46            <string>图标: </string>

 47           </property>

 48          </widget>

 49         </item>

 50         <item>

 51          <widget class="QComboBox" name="comboBoxIcon"/>

 52         </item>

 53         <item>

 54          <spacer name="horizontalSpacer">

 55           <property name="orientation">

 56            <enum>Qt::Horizontal</enum>

 57           </property>

 58           <property name="sizeHint" stdset="0">

 59            <size>

 60             <width>40</width>

 61             <height>20</height>

 62            </size>

 63           </property>

 64          </spacer>

 65         </item>

 66         <item>

 67          <widget class="QCheckBox" name="checkBoxShowIcon">

 68           <property name="text">

 69            <string>展示图标</string>

 70           </property>

 71          </widget>

 72         </item>

 73        </layout>

 74       </item>

 75       <item>

 76        <widget class="QCheckBox" name="checkBoxQQmsg">

 77         <property name="text">

 78          <string>QQ消息效果</string>

 79         </property>

 80        </widget>

 81       </item>

 82      </layout>

 83     </widget>

 84    </item>

 85    <item>

 86     <widget class="QGroupBox" name="groupBoxMessages">

 87      <property name="enabled">

 88       <bool>true</bool>

 89      </property>

 90      <property name="title">

 91       <string>气泡消息</string>

 92      </property>

 93      <layout class="QGridLayout" name="gridLayout">

 94       <item row="2" column="1">

 95        <widget class="QLabel" name="label_5">

 96         <property name="text">

 97          <string>标题: </string>

 98         </property>

 99        </widget>

100       </item>

101       <item row="1" column="1">

102        <widget class="QLabel" name="label_3">

103         <property name="text">

104          <string>持续时长: </string>

105         </property>

106        </widget>

107       </item>

108       <item row="3" column="2">

109        <widget class="QTextEdit" name="textEditContent"/>

110       </item>

111       <item row="0" column="1">

112        <widget class="QLabel" name="label_2">

113         <property name="text">

114          <string>类型: </string>

115         </property>

116        </widget>

117       </item>

118       <item row="0" column="2">

119        <widget class="QComboBox" name="comboBox_MsgInfo">

120         <property name="maximumSize">

121          <size>

122           <width>100</width>

123           <height>16777215</height>

124          </size>

125         </property>

126        </widget>

127       </item>

128       <item row="1" column="2">

129        <widget class="QSpinBox" name="spinBoxTime">

130         <property name="enabled">

131          <bool>true</bool>

132         </property>

133         <property name="sizePolicy">

134          <sizepolicy hsizetype="Minimum" vsizetype="Fixed">

135           <horstretch>60</horstretch>

136           <verstretch>0</verstretch>

137          </sizepolicy>

138         </property>

139         <property name="maximumSize">

140          <size>

141           <width>60</width>

142           <height>16777215</height>

143          </size>

144         </property>

145        </widget>

146       </item>

147       <item row="2" column="2">

148        <widget class="QLineEdit" name="lineEditTitle"/>

149       </item>

150       <item row="3" column="1">

151        <widget class="QLabel" name="label_6">

152         <property name="text">

153          <string>内容: </string>

154         </property>

155         <property name="alignment">

156          <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>

157         </property>

158        </widget>

159       </item>

160       <item row="4" column="2">

161        <widget class="QPushButton" name="ShowButton">

162         <property name="maximumSize">

163          <size>

164           <width>75</width>

165           <height>16777215</height>

166          </size>

167         </property>

168         <property name="text">

169          <string>展示消息</string>

170         </property>

171        </widget>

172       </item>

173      </layout>

174     </widget>

175    </item>

176   </layout>

177  </widget>

178  <resources/>

179  <connections/>

180 </ui>

uic转换为py

trayicon.py文件:

  1 # -*- coding: utf-8 -*-

  2 

  3 # Form implementation generated from reading ui file 'trayicon.ui'

  4 #

  5 # Created: Tue Mar 03 17:34:43 2015

  6 #      by: PyQt4 UI code generator 4.10.3

  7 #

  8 # WARNING! All changes made in this file will be lost!

  9 

 10 from PyQt4 import QtCore, QtGui

 11 

 12 try:

 13     _fromUtf8 = QtCore.QString.fromUtf8

 14 except AttributeError:

 15     def _fromUtf8(s):

 16         return s

 17 

 18 try:

 19     _encoding = QtGui.QApplication.UnicodeUTF8

 20     def _translate(context, text, disambig):

 21         return QtGui.QApplication.translate(context, text, disambig, _encoding)

 22 except AttributeError:

 23     def _translate(context, text, disambig):

 24         return QtGui.QApplication.translate(context, text, disambig)

 25 

 26 class Ui_TrayIcon(object):

 27     def setupUi(self, TrayIcon):

 28         TrayIcon.setObjectName(_fromUtf8("TrayIcon"))

 29         TrayIcon.resize(418, 441)

 30         TrayIcon.setMaximumSize(QtCore.QSize(1024, 16777215))

 31         self.verticalLayout = QtGui.QVBoxLayout(TrayIcon)

 32         self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))

 33         self.groupBoxTrayIcon = QtGui.QGroupBox(TrayIcon)

 34         self.groupBoxTrayIcon.setMinimumSize(QtCore.QSize(400, 100))

 35         self.groupBoxTrayIcon.setMaximumSize(QtCore.QSize(16777215, 100))

 36         self.groupBoxTrayIcon.setObjectName(_fromUtf8("groupBoxTrayIcon"))

 37         self.verticalLayout_2 = QtGui.QVBoxLayout(self.groupBoxTrayIcon)

 38         self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))

 39         self.horizontalLayoutByrayicon = QtGui.QHBoxLayout()

 40         self.horizontalLayoutByrayicon.setObjectName(_fromUtf8("horizontalLayoutByrayicon"))

 41         self.label = QtGui.QLabel(self.groupBoxTrayIcon)

 42         self.label.setObjectName(_fromUtf8("label"))

 43         self.horizontalLayoutByrayicon.addWidget(self.label)

 44         self.comboBoxIcon = QtGui.QComboBox(self.groupBoxTrayIcon)

 45         self.comboBoxIcon.setObjectName(_fromUtf8("comboBoxIcon"))

 46         self.horizontalLayoutByrayicon.addWidget(self.comboBoxIcon)

 47         spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)

 48         self.horizontalLayoutByrayicon.addItem(spacerItem)

 49         self.checkBoxShowIcon = QtGui.QCheckBox(self.groupBoxTrayIcon)

 50         self.checkBoxShowIcon.setObjectName(_fromUtf8("checkBoxShowIcon"))

 51         self.horizontalLayoutByrayicon.addWidget(self.checkBoxShowIcon)

 52         self.verticalLayout_2.addLayout(self.horizontalLayoutByrayicon)

 53         self.checkBoxQQmsg = QtGui.QCheckBox(self.groupBoxTrayIcon)

 54         self.checkBoxQQmsg.setObjectName(_fromUtf8("checkBoxQQmsg"))

 55         self.verticalLayout_2.addWidget(self.checkBoxQQmsg)

 56         self.verticalLayout.addWidget(self.groupBoxTrayIcon)

 57         self.groupBoxMessages = QtGui.QGroupBox(TrayIcon)

 58         self.groupBoxMessages.setEnabled(True)

 59         self.groupBoxMessages.setObjectName(_fromUtf8("groupBoxMessages"))

 60         self.gridLayout = QtGui.QGridLayout(self.groupBoxMessages)

 61         self.gridLayout.setObjectName(_fromUtf8("gridLayout"))

 62         self.label_5 = QtGui.QLabel(self.groupBoxMessages)

 63         self.label_5.setObjectName(_fromUtf8("label_5"))

 64         self.gridLayout.addWidget(self.label_5, 2, 1, 1, 1)

 65         self.label_3 = QtGui.QLabel(self.groupBoxMessages)

 66         self.label_3.setObjectName(_fromUtf8("label_3"))

 67         self.gridLayout.addWidget(self.label_3, 1, 1, 1, 1)

 68         self.textEditContent = QtGui.QTextEdit(self.groupBoxMessages)

 69         self.textEditContent.setObjectName(_fromUtf8("textEditContent"))

 70         self.gridLayout.addWidget(self.textEditContent, 3, 2, 1, 1)

 71         self.label_2 = QtGui.QLabel(self.groupBoxMessages)

 72         self.label_2.setObjectName(_fromUtf8("label_2"))

 73         self.gridLayout.addWidget(self.label_2, 0, 1, 1, 1)

 74         self.comboBox_MsgInfo = QtGui.QComboBox(self.groupBoxMessages)

 75         self.comboBox_MsgInfo.setMaximumSize(QtCore.QSize(100, 16777215))

 76         self.comboBox_MsgInfo.setObjectName(_fromUtf8("comboBox_MsgInfo"))

 77         self.gridLayout.addWidget(self.comboBox_MsgInfo, 0, 2, 1, 1)

 78         self.spinBoxTime = QtGui.QSpinBox(self.groupBoxMessages)

 79         self.spinBoxTime.setEnabled(True)

 80         sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)

 81         sizePolicy.setHorizontalStretch(60)

 82         sizePolicy.setVerticalStretch(0)

 83         sizePolicy.setHeightForWidth(self.spinBoxTime.sizePolicy().hasHeightForWidth())

 84         self.spinBoxTime.setSizePolicy(sizePolicy)

 85         self.spinBoxTime.setMaximumSize(QtCore.QSize(60, 16777215))

 86         self.spinBoxTime.setObjectName(_fromUtf8("spinBoxTime"))

 87         self.gridLayout.addWidget(self.spinBoxTime, 1, 2, 1, 1)

 88         self.lineEditTitle = QtGui.QLineEdit(self.groupBoxMessages)

 89         self.lineEditTitle.setObjectName(_fromUtf8("lineEditTitle"))

 90         self.gridLayout.addWidget(self.lineEditTitle, 2, 2, 1, 1)

 91         self.label_6 = QtGui.QLabel(self.groupBoxMessages)

 92         self.label_6.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)

 93         self.label_6.setObjectName(_fromUtf8("label_6"))

 94         self.gridLayout.addWidget(self.label_6, 3, 1, 1, 1)

 95         self.ShowButton = QtGui.QPushButton(self.groupBoxMessages)

 96         self.ShowButton.setMaximumSize(QtCore.QSize(75, 16777215))

 97         self.ShowButton.setObjectName(_fromUtf8("ShowButton"))

 98         self.gridLayout.addWidget(self.ShowButton, 4, 2, 1, 1)

 99         self.verticalLayout.addWidget(self.groupBoxMessages)

100 

101         self.retranslateUi(TrayIcon)

102         QtCore.QMetaObject.connectSlotsByName(TrayIcon)

103 

104     def retranslateUi(self, TrayIcon):

105         TrayIcon.setWindowTitle(_translate("TrayIcon", "Form", None))

106         self.groupBoxTrayIcon.setTitle(_translate("TrayIcon", "托盘图标", None))

107         self.label.setText(_translate("TrayIcon", "图标: ", None))

108         self.checkBoxShowIcon.setText(_translate("TrayIcon", "展示图标", None))

109         self.checkBoxQQmsg.setText(_translate("TrayIcon", "QQ消息效果", None))

110         self.groupBoxMessages.setTitle(_translate("TrayIcon", "气泡消息", None))

111         self.label_5.setText(_translate("TrayIcon", "标题: ", None))

112         self.label_3.setText(_translate("TrayIcon", "持续时长: ", None))

113         self.label_2.setText(_translate("TrayIcon", "类型: ", None))

114         self.label_6.setText(_translate("TrayIcon", "内容: ", None))

115         self.ShowButton.setText(_translate("TrayIcon", "展示消息", None))

116 

117 

118 if __name__ == "__main__":

119     import sys

120     app = QtGui.QApplication(sys.argv)

121     TrayIcon = QtGui.QWidget()

122     ui = Ui_TrayIcon()

123     ui.setupUi(TrayIcon)

124     TrayIcon.show()

125     sys.exit(app.exec_())

二.逻辑的实现

新建mainTray.py文件,内容:

  1 # -*- coding: UTF8 -*-

  2 # UI说明: 新建窗体,添加两个groupbox  右键 -- 布局 -- 垂直布局

  3 

  4 import sip

  5 sip.setapi('QVariant', 2)

  6 from PyQt4 import QtCore, QtGui

  7 from trayicon import Ui_TrayIcon

  8 import threading

  9 import icoqrc

 10 

 11 

 12 class mainTray(QtGui.QWidget):

 13     def __init__(self):

 14         super(mainTray, self).__init__()

 15         self.Ui= Ui_TrayIcon()

 16         self.Ui.setupUi(self)

 17         self.setWindowTitle(u'Pyqt 托盘效果')

 18         self.setWindowIcon(QtGui.QIcon(':chrome.ico'))

 19         # 填充Ui内容

 20         self.supplyUi()

 21 

 22         # 创建icon

 23         self.createTrayIcon()

 24 

 25         #通知区域icon显示

 26         self.Ui.comboBoxIcon.currentIndexChanged.connect(self.setIcon)  # 链接信号槽

 27         self.Ui.comboBoxIcon.setCurrentIndex(1)  # 设置当前combox

 28         self.trayIcon.activated.connect(self.iconActivated)   # 触发托盘事件

 29         self.Ui.checkBoxShowIcon.toggled.connect(self.trayIcon.setVisible)  # 触发是否显示托盘图标

 30         self.trayIcon.show()  # 托盘show

 31         self.Ui.ShowButton.clicked.connect(self.showMessage)   # 触发展示消息

 32         self.trayIcon.messageClicked.connect(self.messageClicked)   # 点击提示消息

 33         self.threadTask()  # 线程任务

 34         self.Ui.checkBoxQQmsg.toggled.connect(self.QQmsg)  # 触发QQ消息效果

 35 

 36 

 37 

 38 

 39 

 40 

 41     def supplyUi(self):

 42         # 托盘图标

 43         self.Ui.comboBoxIcon.addItem(QtGui.QIcon(':chrome.ico'), u'Chrome')

 44         self.Ui.comboBoxIcon.addItem(QtGui.QIcon(':firefox.ico'), u'Firefox')

 45         self.Ui.comboBoxIcon.addItem(QtGui.QIcon(':qq.ico'), u'QQ')

 46         self.Ui.comboBoxIcon.addItem(QtGui.QIcon(':flash.ico'), u'Flash')

 47         self.Ui.comboBoxIcon.addItem(QtGui.QIcon(':ie.ico'), u'IE')

 48         self.Ui.comboBoxIcon.addItem(QtGui.QIcon(':myfavicon.ico'), u'Favicon')

 49 

 50         # 默认展示托盘图标

 51         self.Ui.checkBoxShowIcon.setChecked(True)

 52 

 53         # 消息combox

 54         self.Ui.comboBox_MsgInfo.addItem("None", QtGui.QSystemTrayIcon.NoIcon)

 55         self.Ui.comboBox_MsgInfo.addItem(self.style().standardIcon(QtGui.QStyle.SP_MessageBoxInformation), u"信息提示", QtGui.QSystemTrayIcon.Information)

 56         self.Ui.comboBox_MsgInfo.addItem(self.style().standardIcon(QtGui.QStyle.SP_MessageBoxWarning), u"警告提示",  QtGui.QSystemTrayIcon.Warning)

 57         self.Ui.comboBox_MsgInfo.addItem(self.style().standardIcon(QtGui.QStyle.SP_MessageBoxCritical), u"严重警告",   QtGui.QSystemTrayIcon.Critical)

 58 

 59         # 时长显示

 60         self.Ui.spinBoxTime.setRange(5, 60)  # spinbox 在5--60 之间

 61         self.Ui.spinBoxTime.setSuffix(" s")  # 设置后缀  s  秒

 62         self.Ui.spinBoxTime.setValue(15)  # 默认值为15秒

 63 

 64         # 设置 标题和提示的初始化内容

 65         self.Ui.lineEditTitle.setText(u'无法连接到网络')

 66         self.Ui.textEditContent.setText(u'您的电脑无法连接到网络,请确保已经接入Internet,or WLAN 端口已经插好! 有问题请致电:<b>1389876543</b>')

 67     #  创建icon 与菜单

 68     def createTrayIcon(self):

 69         self.minimizeAction = QtGui.QAction(u"最小化", self, triggered=self.hide)

 70         self.maximizeAction = QtGui.QAction(u"最大化", self, triggered=self.showMaximized)

 71         self.restoreAction = QtGui.QAction(u"还原大小", self, triggered=self.showNormal)

 72         self.quitAction = QtGui.QAction(u"退出", self, triggered=QtGui.qApp.quit)

 73         self.trayIconMenu = QtGui.QMenu(self)

 74         self.trayIconMenu.addAction(self.minimizeAction)

 75         self.trayIconMenu.addAction(self.maximizeAction)

 76         self.trayIconMenu.addAction(self.restoreAction)

 77         self.trayIconMenu.addSeparator()  # 分割行

 78         self.trayIconMenu.addAction(self.quitAction)

 79         self.trayIcon = QtGui.QSystemTrayIcon(self)

 80         self.trayIcon.setContextMenu(self.trayIconMenu)

 81     # 触发托盘icon

 82     def iconActivated(self, reason):

 83         if reason in (QtGui.QSystemTrayIcon.Trigger, QtGui.QSystemTrayIcon.DoubleClick):

 84             self.Ui.comboBoxIcon.setCurrentIndex((self.Ui.comboBoxIcon.currentIndex() + 1) % self.Ui.comboBoxIcon.count())

 85         elif reason == QtGui.QSystemTrayIcon.MiddleClick:   # 点击鼠标滚动轴事件

 86             self.showMessage()

 87     # 设置icon

 88     def setIcon(self, index):

 89         icon = self.Ui.comboBoxIcon.itemIcon(index)

 90         self.trayIcon.setIcon(icon)

 91         self.setWindowIcon(icon)

 92         self.trayIcon.setToolTip(self.Ui.comboBoxIcon.itemText(index))

 93 

 94     # 展示消息

 95     def showMessage(self):

 96         icon = QtGui.QSystemTrayIcon.MessageIcon(self.Ui.comboBox_MsgInfo.itemData(self.Ui.comboBox_MsgInfo.currentIndex()))

 97         self.trayIcon.showMessage(self.Ui.lineEditTitle.text(),  self.Ui.textEditContent.toPlainText(), icon, self.Ui.spinBoxTime.value() * 1000)

 98 

 99     # 点击消息

100     def messageClicked(self):

101         QtGui.QMessageBox.information(None, "Systray","Sorry, I already gave what help I could.\nMaybe you should "  "try asking a human?")

102 

103     # 添加一个线程

104     def threadTask(self):

105         global t

106         t = threading.Timer(6.0, self.showMessage)  # 6秒后执行显示消息

107         t.start()

108 

109     def QQmsg(self):

110         import time

111         status = self.Ui.checkBoxQQmsg.isChecked()

112         comboxicoIndex = self.Ui.comboBoxIcon.currentIndex()

113         icon = self.Ui.comboBoxIcon.itemIcon(comboxicoIndex)

114         arrs = 1

115         whiles = 1

116         if status:

117             while whiles <= 6:

118                 if arrs == 1:

119                     time.sleep(0.6)

120                     self.trayIcon.setIcon(QtGui.QIcon())

121                     arrs = 2

122                 else:

123                     time.sleep(0.6)

124                     self.trayIcon.setIcon(icon)

125                     arrs = 1

126                 whiles += 1

127 

128         else:

129             self.trayIcon.setIcon(icon)

130 

131 

132     def keyPressEvent(self, event):

133         if event.key() ==QtCore.Qt.Key_Escape:

134             self.hide()

135 

136 if __name__ == '__main__':

137     import sys

138     app = QtGui.QApplication(sys.argv)

139     QtGui.QApplication.setQuitOnLastWindowClosed(False)

140     trany = mainTray()

141     trany.show()

142     sys.exit(app.exec_())

三.效果

Pyqt QSystemTrayIcon 实现托盘效果

Pyqt QSystemTrayIcon 实现托盘效果

Pyqt QSystemTrayIcon 实现托盘效果

 

四.打包出现问题

使用pyinstaller 打包exe,运行不了,即使打包Pyqt4里面的demo 也运行不了,目前未找到原因!

你可能感兴趣的:(System)