本文整理汇总了Python中PyQt5.QtWidgets.QSystemTrayIcon.showMessage方法的典型用法代码示例。如果您正苦于以下问题:Python QSystemTrayIcon.showMessage方法的具体用法?Python QSystemTrayIcon.showMessage怎么用?Python QSystemTrayIcon.showMessage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QSystemTrayIcon
的用法示例。
在下文中一共展示了QSystemTrayIcon.showMessage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SystemTray
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
class SystemTray(QWidget):
def __init__(self, parent=None):
super(SystemTray, self).__init__(parent)
self.tray_icon_menu = QMenu(self)
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setContextMenu(self.tray_icon_menu)
self.icon_management = IconManagement(self.tray_icon)
self.connection_handler = ConnectionHandler(FREQUENCY_CHECK_MS, TIME_OUT_CALL_S, self)
self.connection_handler.value_changed.connect(self.internet_connection)
self.connection_handler.start()
def add_action(self, name, triggered_action):
action = QAction(QCoreApplication.translate(trad_context, name), self, triggered = triggered_action)
self.tray_icon_menu.addAction(action)
def add_separator(self):
self.tray_icon_menu.addSeparator()
def show(self):
super(SystemTray, self).show()
self.tray_icon.show()
@pyqtSlot()
def event_started(self):
self.icon_management.start()
@pyqtSlot()
def event_finished(self):
self.icon_management.stop()
@pyqtSlot(Exception)
def conductor_problem(self, e):
self.notify("Demerio", "There was a problem : %s" % (e,))
self.icon_management.conductor_problem()
@pyqtSlot(bool)
def internet_connection(self, internet_is_ok):
if not internet_is_ok:
self.notify("Demerio", "Internet connection is lost")
self.icon_management.internet_is_ok(internet_is_ok)
def notify(self, title, message):
self.tray_icon.showMessage(title, message, BAR_NOTIFICATION_TIME)
示例2: Magneto
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
#.........这里部分代码省略.........
if done:
self._menu_items["disable_applet"].setEnabled(True)
self._menu_items["enable_applet"].setEnabled(False)
def show_alert(self, title, text, urgency = None, force = False,
buttons = None):
# NOTE: there is no support for buttons via QSystemTrayIcon.
if ((title, text) == self.last_alert) and not force:
return
def _action_activate_cb(action_num):
if not buttons:
return
try:
action_info = buttons[action_num - 1]
except IndexError:
return
_action_id, _button_name, button_callback = action_info
button_callback()
def do_show():
if not self._window.supportsMessages():
const_debug_write("show_alert", "messages not supported.")
return
icon_id = QSystemTrayIcon.Information
if urgency == "critical":
icon_id = QSystemTrayIcon.Critical
self._window.showMessage(title, text, icon_id)
self.last_alert = (title, text)
QTimer.singleShot(0, do_show)
def update_tooltip(self, tip):
def do_update():
self._window.setToolTip(tip)
QTimer.singleShot(0, do_update)
def applet_context_menu(self):
"""No action for now."""
def _applet_activated(self, reason):
const_debug_write("applet_activated", "Applet activated: %s" % reason)
if reason == QSystemTrayIcon.DoubleClick:
const_debug_write("applet_activated", "Double click event.")
self.applet_doubleclick()
def hide_notice_window(self):
self.notice_window_shown = False
self._notice_window.hide()
def show_notice_window(self):
if self.notice_window_shown:
const_debug_write("show_notice_window", "Notice window already shown.")
return
if not self.package_updates:
const_debug_write("show_notice_window", "No computed updates.")
return
示例3: ZhaoChaFrame
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
class ZhaoChaFrame(QWidget):
game_hwnd = 0 # 游戏的窗体句柄
bgpixmap = None
pixmap = None
my_visible = False
# GAME_CLASS = "#32770"
# GAME_TITLE = "大家来找茬"
GAME_CLASS = "MozillaWindowClass"
GAME_TITLE = "游戏全屏 - Mozilla Firefox"
WIDTH = 500 # 大图宽
HEIGHT = 450 # 大图高
ANCHOR_LEFT_X = 8 # 左图X起点
ANCHOR_RIGHT_X = 517 # 右图X起点
ANCHOR_Y = 190 # Y起点
CLIP_WIDTH = 10
CLIP_HEIGHT = 10
DIFF_LIMIT = 2000 # 差异阀值,两片图形对比差异差异超过此值视为不一样
# 查找区域
# 大图版 1024 x 738
BIG_WIDTH = 498 # 大图宽
BIG_HEIGHT = 448 # 大图高
BIG_ANCHOR_LEFT_X = 8 # 左图X起点
BIG_ANCHOR_RIGHT_X = 517 # 右图X起点
BIG_ANCHOR_Y = 190 # Y起点
BIG_CLIP_WIDTH = 10
BIG_CLIP_HEIGHT = 10
BIG_DIFF_LIMIT = 2000 # 差异阀值,两片图形对比差异差异超过此值视为不一样
# 小图版 800 x 600
SMALL_WIDTH = 381 # 大图宽
SMALL_HEIGHT = 286 # 大图高
SMALL_ANCHOR_LEFT_X = 10 # 左图X起点
SMALL_ANCHOR_RIGHT_X = 403 # 右图X起点
SMALL_ANCHOR_Y = 184 # Y起点
SMALL_CLIP_WIDTH = 10
SMALL_CLIP_HEIGHT = 10
SMALL_DIFF_LIMIT = 2000 # 差异阀值,两片图形对比差异差异超过此值视为不一样
# 存储对比结果 二位数组,映射每一个基块
result = []
clock = 0
def __init__(self, parent=None):
QWidget.__init__(self)
# QWidget.__init__(self, parent, flags=Qt.FramelessWindowHint | Qt.Window | Qt.WindowStaysOnTopHint)
# 设置背景透明,这样按钮不会太难看
# self.setAttribute(Qt.WA_TranslucentBackground, True)
# 这些属性让程序不在任务栏出现标题
# self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Popup | Qt.Tool)
# 托盘
self.icon = QIcon(":\icon.png")
self.trayIcon = QSystemTrayIcon(self)
self.trayIcon.setIcon(self.icon)
self.trayIcon.setToolTip(u"QQ找茬助手")
self.trayIcon.show()
self.trayIcon.showMessage(u"QQ找茬助手", u"QQ找茬助手已经待命,进入游戏即可激活")
self.action = QAction(u"退出QQ找茬助手", self, triggered=sys.exit)
self.menu = QMenu(self)
self.menu.addAction(self.action)
self.trayIcon.setContextMenu(self.menu)
# 定时探测游戏
self.stick_timer = QTimer()
self.stick_timer.start(20)
# self.connect(self.stick_timer, SIGNAL('timeout()'), self.StickTarget)
# 这个QLabel其实就是中间绘图区的背景
self.label = QLabel(self)
self.pixmap = QPixmap(self.size())
# 刷新按钮
self.btn_compare = QPushButton(self)
self.btn_compare.setText(u"对比")
# self.connect(self.btn_compare, SIGNAL('clicked()'), self.Compare)
# 开关
self.btn_toggle = QPushButton(self)
self.btn_toggle.setText(u"擦除")
# self.connect(self.btn_toggle, SIGNAL('clicked()'), self.Clear)
self.HideMe()
def StickTarget(self):
'''让本窗体粘附在目标窗体上'''
# 找到目标窗口句柄
game_hwnd = win32gui.FindWindow(self.GAME_CLASS, self.GAME_TITLE)
if game_hwnd == 0:
if self.my_visible:
# 如果游戏窗体不可见,比如最小化、关闭了,隐藏自己
#.........这里部分代码省略.........
示例4: DemoImpl
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
class DemoImpl(QDialog):
def __init__(self, *args):
super(DemoImpl, self).__init__(*args)
loadUi('dict2.ui',self)
self.setLayout(self.verticalLayout)
self.plainTextEdit.setReadOnly(True)
self.setWindowFlags(self.windowFlags() |
Qt.WindowSystemMenuHint |
Qt.WindowMinMaxButtonsHint)
self.trayicon = QSystemTrayIcon()
self.traymenu = QMenu()
self.quitAction = QAction('GQuit', self)
self.quitAction.triggered.connect(self.close)
self.quitAction.setShortcut(QKeySequence('Ctrl+q'))
self.addAction(self.quitAction)
self.traymenu.addAction('&Normal', self.showNormal, QKeySequence('Ctrl+n'))
self.traymenu.addAction('Mi&nimize', self.showMinimized, QKeySequence('Ctrl+i'))
self.traymenu.addAction('&Maximum', self.showMaximized, QKeySequence('Ctrl+m'))
self.traymenu.addAction('&Quit',self.close, QKeySequence('Ctrl+q'))
self.trayicon.setContextMenu(self.traymenu)
self.ticon = QIcon('icon_dict2.ico')
self.trayicon.setIcon(self.ticon)
self.trayicon.setToolTip('YYDict')
self.trayicon.activated.connect(self.on_systemTrayIcon_activated)
self.traymsg_firstshow = True
self.button1.clicked.connect(self.searchword)
self.comboBox.activated.connect(self.searchword)
def changeEvent(self, event):
if event.type() == QEvent.WindowStateChange:
if self.isMinimized():
self.hide()
self.trayicon.show()
if self.traymsg_firstshow:
self.trayicon.showMessage('', 'YYDict is running', QSystemTrayIcon.Information, 2000)
self.traymsg_firstshow = False
else:
self.trayicon.hide()
def closeEvent(self, event):
self.trayicon.hide()
@pyqtSlot(QSystemTrayIcon.ActivationReason)
def on_systemTrayIcon_activated(self, reason):
if reason == QSystemTrayIcon.DoubleClick:
self.activateWindow()
self.showNormal()
@pyqtSlot()
def searchword(self):
word = self.lineEdit.text().strip()
if not len(word):
self.plainTextEdit.setPlainText('')
self.lineEdit.setFocus(Qt.MouseFocusReason)
else:
self.workThread = WorkThread(word, self.comboBox.currentIndex())
self.workThread.received.connect(self.updateResult)
self.workThread.start()
self.workThread.wait()
@pyqtSlot('QString')
def updateResult(self, rt):
self.plainTextEdit.setPlainText(rt)
self.lineEdit.selectAll()
self.lineEdit.setFocus(Qt.MouseFocusReason)
示例5: TriblerWindow
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
#.........这里部分代码省略.........
def on_torrent_finished(self, torrent_info):
self.tray_show_message("Download finished", "Download of %s has finished." % torrent_info["name"])
def show_loading_screen(self):
self.top_menu_button.setHidden(True)
self.left_menu.setHidden(True)
self.token_balance_widget.setHidden(True)
self.settings_button.setHidden(True)
self.add_torrent_button.setHidden(True)
self.top_search_bar.setHidden(True)
self.stackedWidget.setCurrentIndex(PAGE_LOADING)
def tray_set_tooltip(self, message):
"""
Set a tooltip message for the tray icon, if possible.
:param message: the message to display on hover
"""
if self.tray_icon:
try:
self.tray_icon.setToolTip(message)
except RuntimeError as e:
logging.error("Failed to set tray tooltip: %s", str(e))
def tray_show_message(self, title, message):
"""
Show a message at the tray icon, if possible.
:param title: the title of the message
:param message: the message to display
"""
if self.tray_icon:
try:
self.tray_icon.showMessage(title, message)
except RuntimeError as e:
logging.error("Failed to set tray message: %s", str(e))
def on_tribler_started(self):
self.tribler_started = True
self.top_menu_button.setHidden(False)
self.left_menu.setHidden(False)
self.token_balance_widget.setHidden(False)
self.settings_button.setHidden(False)
self.add_torrent_button.setHidden(False)
self.top_search_bar.setHidden(False)
# fetch the settings, needed for the video player port
self.request_mgr = TriblerRequestManager()
self.fetch_settings()
self.downloads_page.start_loading_downloads()
self.home_page.load_popular_torrents()
if not self.gui_settings.value("first_discover", False) and not self.core_manager.use_existing_core:
self.window().gui_settings.setValue("first_discover", True)
self.discovering_page.is_discovering = True
self.stackedWidget.setCurrentIndex(PAGE_DISCOVERING)
else:
self.clicked_menu_button_home()
self.setAcceptDrops(True)
def on_events_started(self, json_dict):
self.setWindowTitle("Tribler %s" % json_dict["version"])
def show_status_bar(self, message):
示例6: Example
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
self.trayIcon = None
self.kill = False
self.setupTrayIcon()
try:
cherrypy_server.start_server()
except Exception as e:
logging.getLogger(__name__).warn("Problem starting print server! {}".format(e))
traceback.print_exc()
def reallyClose(self):
self.kill = True
self.close()
def openConsole(self):
from web.server import cfg
url = r'https://localhost:{}'.format(cfg.port)
webbrowser.open(url)
def initUI(self):
openAction = QAction("&Open Console", self)
openAction.setShortcut('Ctrl+O')
openAction.setStatusTip('Open Console')
openAction.triggered.connect(self.openConsole)
exitAction = QAction(QIcon(os.path.join('web', 'static', 'img', 'exit-icon-3.png')), '&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(self.reallyClose)
self.statusBar()
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(openAction)
fileMenu.addSeparator()
fileMenu.addAction(exitAction)
wrapper = QWidget()
txt = QTextEdit()
txt.setReadOnly(True)
txt.setLineWrapMode(QTextEdit.NoWrap)
txt.setUndoRedoEnabled(False)
txt.setAcceptDrops(False)
txt.setAcceptRichText(False)
font = txt.font()
font.setFamily("Courier")
font.setPointSize(9)
txt.setFont(font)
policy = txt.sizePolicy()
policy.setVerticalStretch(1)
txt.setSizePolicy(policy)
layout = QGridLayout()
layout.addWidget(txt)
wrapper.setLayout(layout)
self.setCentralWidget(wrapper)
def _write(s):
txt.moveCursor(QTextCursor.End)
txt.insertPlainText(str(s))
txt.moveCursor(QTextCursor.End)
setup_logging(_write)
self.setGeometry(300, 300, 800, 600)
self.setWindowTitle('Antix Print Server')
def setupTrayIcon(self):
_icon = QIcon(os.path.join('web', 'static', 'img', 'Logo.144x144.png'))
self.trayIcon = QSystemTrayIcon(_icon, self)
menu = QMenu(self)
menu.addAction("Show", self.show)
menu.addAction("Hide", self.hide)
menu.addAction("Exit", self.reallyClose)
self.trayIcon.setContextMenu(menu)
self.trayIcon.show()
self.trayIcon.showMessage("Antix Printer Server", "Is running")
def closeEvent(self, evnt):
if self.kill:
self.trayIcon.hide()
try:
cherrypy_server.stop_server()
except Exception as e:
logging.getLogger(__name__).warn("Problem stopping server! {}".format(e))
qApp.exit(0)
else:
evnt.ignore()
self.hide()
示例7: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
#.........这里部分代码省略.........
tools.setIcon(QtGui.QIcon(appfolder + '/ressource/icons/postgresql.png'))
tools_postgre_restart = QAction(QtGui.QIcon(self.icon), "Restart Server", self)
tools_postgre_restart.triggered.connect(lambda: (self.restartPostgreMenuItem.emit()))
tools.addAction(tools_postgre_restart)
tools_postgre_restart.setIcon(QtGui.QIcon(appfolder + '/ressource/icons/start_server.png'))
tools_postgre_stop = QAction(QtGui.QIcon(self.icon), "Stop Server", self)
tools_postgre_stop.triggered.connect(lambda: (self.stopPostgreMenuItem.emit()))
tools.addAction(tools_postgre_stop)
tools_postgre_stop.setIcon(QtGui.QIcon(appfolder + '/ressource/icons/stop_server.png'))
tools.addSeparator()
tools_pgadmin = QAction(QtGui.QIcon(self.icon), "pgAdmin III", self)
tools_pgadmin.triggered.connect(lambda: self.startpgadmin())
tools.addAction(tools_pgadmin)
tools_pgadmin.setIcon(QtGui.QIcon(appfolder + '/ressource/icons/cog.png'))
traymenu.addSeparator()
trayoption_quickconfig = QAction(QtGui.QIcon(self.icon), "Show Output/Config", self)
trayoption_quickconfig.triggered.connect(lambda: self.showCommandLineWindowTryOption())
traymenu.addAction(trayoption_quickconfig)
trayoption_quickconfig.setIcon(QtGui.QIcon(appfolder + '/ressource/icons/application_osx_terminal.png'))
traymenu.addSeparator()
trayoption_exit_entry = QAction(QtGui.QIcon(self.icon), "Exit", self)
trayoption_exit_entry.triggered.connect(lambda: self.trayOptionExit())
traymenu.addAction(trayoption_exit_entry)
trayoption_exit_entry.setIcon(QtGui.QIcon(appfolder + '/ressource/icons/cancel.png'))
self.tray.showMessage('Odoo is Loading - Please wait','\nLeft click to open CommandWindow\nRight click to open Traymenu')
self.showCommandLineWindow()
def startpgadmin(self):
os.startfile(appfolder + '/Runtime/PostgreSQL/bin/pgAdmin3.exe')
def showCommandLineWindow(self):
self.ShowCommandLineWindow=CommandLineWindow(self)
self.ShowCommandLineWindow.setWindowIcon(QtGui.QIcon(appfolder + '/ressource/icons/icon.png'))
self.ShowCommandLineWindow.show()
if mainSettings['other']['minimizeToTray']:
self.ShowCommandLineWindow.setVisible(False)
else:
self.ShowCommandLineWindow.setVisible(True)
def toggleCommandLineWindow(self):
if self.ShowCommandLineWindow.isMinimized():
self.ShowCommandLineWindow.setVisible(True)
self.ShowCommandLineWindow.showNormal()
self.ShowCommandLineWindow.activateWindow()
elif self.ShowCommandLineWindow.isVisible ():
self.ShowCommandLineWindow.showNormal()
self.ShowCommandLineWindow.setVisible(False)
else:
self.ShowCommandLineWindow.setVisible(True)
self.ShowCommandLineWindow.showNormal()
self.ShowCommandLineWindow.activateWindow()
def showCommandLineWindowTryOption(self):
self.ShowCommandLineWindow.setVisible(True)
self.ShowCommandLineWindow.showNormal()
self.ShowCommandLineWindow.activateWindow()
示例8: SystemTrayIcon
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
#.........这里部分代码省略.........
self.window_visible = True
except:
pass
self.systray.setToolTip(self.tr('Fetching weather data ...'))
self.city = self.settings.value('City') or ''
self.id_ = self.settings.value('ID') or None
if self.id_ is None:
# Clear the menu, no cities configured
self.citiesMenu.clear()
self.empty_cities_list()
# Sometimes self.overviewcity is in namespace but deleted
try:
self.overviewcity.close()
except:
e = sys.exc_info()[0]
logging.error('Error closing overviewcity: ' + str(e))
pass
self.timer.singleShot(2000, self.firsttime)
self.id_ = ''
self.systray.setToolTip(self.tr('No city configured'))
return
# A city has been found, create the cities menu now
self.cities_menu()
self.country = self.settings.value('Country') or ''
self.unit = self.settings.value('Unit') or 'metric'
self.suffix = ('&mode=xml&units=' + self.unit + self.appid)
self.interval = int(self.settings.value('Interval') or 30)*60*1000
self.timer.start(self.interval)
self.update()
def firsttime(self):
self.temp = ''
self.wIcon = QPixmap(':/noicon')
self.systray.showMessage(
'meteo-qt:\n', self.tr('No city has been configured yet.') +
'\n' + self.tr('Right click on the icon and click on Settings.'))
def update(self):
if hasattr(self, 'downloadThread'):
if self.downloadThread.isRunning():
logging.debug('remaining thread...')
return
logging.debug('Update...')
self.icon_loading()
self.wIcon = QPixmap(':/noicon')
self.downloadThread = Download(
self.wIconUrl, self.baseurl, self.forecast_url,
self.day_forecast_url, self.id_, self.suffix)
self.downloadThread.wimage['PyQt_PyObject'].connect(self.makeicon)
self.downloadThread.finished.connect(self.tray)
self.downloadThread.xmlpage['PyQt_PyObject'].connect(self.weatherdata)
self.downloadThread.forecast_rawpage.connect(self.forecast)
self.downloadThread.day_forecast_rawpage.connect(self.dayforecast)
self.downloadThread.uv_signal.connect(self.uv)
self.downloadThread.error.connect(self.error)
self.downloadThread.done.connect(self.done, Qt.QueuedConnection)
self.downloadThread.start()
def uv(self, value):
self.uv_coord = value
def forecast(self, data):
self.forecast_data = data
def dayforecast(self, data):
self.dayforecast_data = data
示例9: PymodoroGUI
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
class PymodoroGUI(QWidget):
"""
GUI for Pymodoro
"""
def __init__(self):
"""
Initializer for the Pomodoro GUI class
"""
super(PymodoroGUI, self).__init__()
self.res_dir = os.path.join("../ext/")
self.green_tomato_icon = os.path.join(self.res_dir, "greentomato.png")
self.red_tomato_icon = os.path.join(self.res_dir, "redtomato.png")
self.tray = QSystemTrayIcon(QIcon(self.green_tomato_icon))
self.pom = Pomodoro()
self.pom.ringer.connect(self.signal)
self.init_ui()
def signal(self, pomodori):
"""
Callback given to the Pomodoro class.
Called when a pomodoro is up
"""
if pomodori % 4 == 0 and pomodori != 0:
self.tray.showMessage("4 Pomodori has passed!",
"Take a long break: 15-30min",
QSystemTrayIcon.Information)
else:
self.tray.showMessage("Pomodoro's up!",
"Take a short break: 3-5min",
QSystemTrayIcon.Information)
self.tray.setIcon(QIcon(self.green_tomato_icon))
def init_tray(self):
"""
Initializes the systray menu
"""
traymenu = QMenu("Menu")
self.tray.setContextMenu(traymenu)
self.tray.show()
self.tray.activated.connect(self.tray_click)
self.tray.setToolTip("Pomodori: "+str(self.pom.pomodori))
set_timer_tray = QLineEdit()
set_timer_tray.setPlaceholderText("Set timer")
set_timer_tray.textChanged.connect(lambda:
self.update_timer_text(set_timer_tray.text()))
traywidget = QWidgetAction(set_timer_tray)
traywidget.setDefaultWidget(set_timer_tray)
traymenu.addAction(traywidget)
start_timer_action = QAction("&Start Timer", self)
start_timer_action.triggered.connect(self.start_timer_click)
traymenu.addAction(start_timer_action)
exit_action = QAction("&Exit", self)
exit_action.triggered.connect(QCoreApplication.instance().quit)
traymenu.addAction(exit_action)
def tray_click(self, activation):
"""
Method called when clicking the tray icon
"""
if activation == QSystemTrayIcon.Trigger:
if self.isVisible():
self.hide()
else:
self.show()
elif activation == QSystemTrayIcon.Context:
self._tray.show()
def close_event(self, event):
self._tray.showMessage("Running in system tray",
"""The program will keep running in the system tray.\n
To terminate the program choose exit from the context menu""",
QSystemTrayIcon.Information)
self.hide()
event.ignore()
def wheel_event(self, event):
if event.delta() > 0:
timervalue = int(self.settimertext.text())
timervalue = timervalue + 1
self.settimertext.setText(str(timervalue))
else:
timervalue = int(self.settimertext.text())
timervalue = timervalue - 1
self.settimertext.setText(str(timervalue))
def init_ui(self):
"""
Initializes the GUI
"""
self.init_tray()
resolution = QApplication.desktop().availableGeometry()
width = 150
height = 100
# place exactly in center of screen
self.setGeometry((resolution.width() / 2) - (width / 2),
#.........这里部分代码省略.........
示例10: Parse99
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
class Parse99(QApplication):
def __init__(self, *args):
super(QApplication, self).__init__(*args)
# Tray Icon
self._system_tray = QSystemTrayIcon()
self._system_tray.setIcon(QIcon('ui/icon.png'))
self._system_tray.setToolTip("Parse99")
self._system_tray.show()
# Settings
self.settings = settings.Settings("parse99")
# Plugins
self._plugins = {'maps': Maps(self.settings)}
# Timer
self._timer = QTimer()
self._timer.timeout.connect(self._parse)
# Thread
self._thread = None
# Menu
self._system_tray.setContextMenu(self._get_menu())
# File
self._log_file = ""
self._file_size = 0
self._last_line_read = 0
self._log_new_lines = []
# Start
self.toggle('on')
def _settings_valid(self):
valid = True
if self.settings.get_value('general', 'first_run') is None:
self._system_tray.showMessage(
"Parse99",
"""It looks like this is the first time the program is being
run. Please setup the application using the Settings option
once you right click the system tray icon."""
)
self.edit_settings()
self.settings.set_value('general', 'first_run', True)
valid = False
elif self.settings.get_value('general', 'eq_directory') is None:
self._system_tray.showMessage(
"Parse99",
"Please enter the General settings and \
choose the location of your Everquest Installation."
)
self.edit_settings()
valid = False
elif self.settings.get_value('characters', None) is None:
self._system_tray.showMessage(
"Parse99",
"No characters have been made. \
Please create at least one character using settings."
)
self.edit_settings(tab="characters")
valid = False
elif self.settings.get_value('general', 'current_character') is None:
self._system_tray.showMessage(
"Parse99",
"No character has been selected. \
Please choose a character from the Character menu."
)
valid = False
return valid
def toggle(self, switch):
if switch == 'off':
if self._thread is not None:
self._timer.stop()
self._thread.stop()
self._thread.join()
elif switch == 'on':
if self._settings_valid():
characters = self.settings.get_value('characters', None)
log_file = characters[
self.settings.get_value('general', 'current_character')
]['log_file']
self._thread = FileReader(
log_file,
int(self.settings.get_value('general', 'parse_interval'))
)
self._thread.start()
self._timer.start(
1000 *
int(self.settings.get_value('general', 'parse_interval'))
)
def _parse(self):
for line in self._thread.get_new_lines():
for plugin in self._plugins.keys():
if self._plugins[plugin].is_active():
self._plugins[plugin].parse(line)
#.........这里部分代码省略.........
示例11: Window
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
class Window(QMainWindow):
"""
Main GUI class for application
"""
def __init__(self):
QWidget.__init__(self)
# loaind ui from xml
uic.loadUi(os.path.join(DIRPATH, 'app.ui'), self)
# self.show_msgbox("Info", "Lan Messenger")
self.users = {}
self.host = socket.gethostname()
self.ip = get_ip_address()
# button event handlers
self.btnRefreshBuddies.clicked.connect(self.refreshBuddies)
self.btnSend.clicked.connect(self.sendMsg)
self.lstBuddies.currentItemChanged.connect(
self.on_buddy_selection_changed)
self.msg_manager = MessageManager()
self.msg_sender = MessageSender(self.host, self.ip)
self.message_listener = MessageListener()
self.message_listener.message_received.connect(self.handle_messages)
self.send_IAI()
self.setup_tray_menu()
# setting up handlers for menubar actions
self.actionAbout.triggered.connect(self.about)
self.actionExit.triggered.connect(qApp.quit)
self.actionPreferences.triggered.connect(self.show_preferences)
def about(self):
print("about")
ad = AboutDialog()
ad.display()
def show_preferences(self):
print("preferences")
pd = PrefsDialog()
pd.display()
def setup_tray_menu(self):
# setting up QSystemTrayIcon
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(
self.style().standardIcon(QStyle.SP_ComputerIcon))
# tray actions
show_action = QAction("Show", self)
quit_action = QAction("Exit", self)
hide_action = QAction("Hide", self)
# action handlers
show_action.triggered.connect(self.show)
hide_action.triggered.connect(self.hide)
quit_action.triggered.connect(qApp.quit)
# tray menu
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()
def closeEvent(self, event):
event.ignore()
self.hide()
self.tray_icon.showMessage(
"PyLanMessenger",
"PyLanMessenger was minimized to Tray",
QSystemTrayIcon.Information,
2000
)
def handle_messages(self, data):
log.debug("UI handling message: %s" % data)
pkt = Packet()
pkt.json_to_obj(data)
if pkt.op == "IAI":
self.handle_IAI(pkt.ip, pkt.host)
if pkt.op == "MTI":
self.handle_MTI(pkt.ip, pkt.host)
if pkt.op == "TCM":
self.handle_TCM(pkt.ip, pkt.host, pkt.msg)
def send_IAI(self):
# broadcast a message that IAI - "I Am In" the n/w
pkt = Packet(op="IAI", ip=self.ip, host=self.host).to_json()
self.msg_sender.send_broadcast_message(pkt)
#.........这里部分代码省略.........
示例12: Onkyo
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
#.........这里部分代码省略.........
self.mainLayout.addWidget(self.btn_usbstop, 2, 0)
self.mainLayout.addWidget(self.btn_usbplay, 2, 1)
self.mainLayout.addWidget(self.btn_usbpause, 2, 2)
self.mainLayout.addWidget(self.btn_usbprew, 2, 3)
self.mainLayout.addWidget(self.btn_usbnext, 2, 4)
self.mainLayout.addWidget(self.btn_poweroff, 4, 0, 1, 2)
self.mainLayout.addWidget(self.btn_mute, 3, 3, 1, 2)
self.mainLayout.addWidget(self.btn_quit, 4, 3, 1, 2)
self.mainWidget.setLayout(self.mainLayout)
self.setCentralWidget(self.mainWidget)
self.setWindowIcon(QIcon('/usr/share/icons/onkyo.png'))
self.setFixedSize(280, 200)
self.setWindowTitle('Onkyo Control')
if self.hide_window:
self.hide()
else:
self.show()
self.createActions()
self.createTrayIcon()
self.createShortcuts()
self.trayIcon.show()
self.statusBar()
self.createMenu()
def createShortcuts(self):
self.shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
self.shortcut.activated.connect(QApplication.instance().quit)
self.shortcut = QShortcut(QKeySequence("Ctrl+M"), self)
self.shortcut.activated.connect(self.btn_mute_click)
def createActions(self):
self.minimizeAction = QAction("Mi&nimize", self, triggered=self.hide)
self.maximizeAction = QAction("Ma&ximize", self, triggered=self.showMaximized)
self.restoreAction = QAction(QIcon('/usr/share/icons/onkyo_restore.png'), "&Restore", self, triggered=self.showNormal)
self.quitAction = QAction(QIcon('/usr/share/icons/onkyo_exit.png'), "&Quit", self, triggered=QApplication.instance().quit)
self.PoweroffAction = QAction(QIcon('/usr/share/icons/onkyo_poweroff.png'), "&Power OFF", self, triggered=self.btn_poweroff_click)
self.MuteAction = QAction(QIcon('/usr/share/icons/onkyo_mute.png'), "&Mute", self, triggered=self.btn_mute_click)
self.VolumeupAction = QAction(QIcon('/usr/share/icons/onkyo_volumeup.png'), "&Volume UP", self, triggered=self.btn_volumeup_click)
self.VolumedownAction = QAction(QIcon('/usr/share/icons/onkyo_volumedown.png'), "&Volume Down", self, triggered=self.btn_volumedown_click)
self.aboutAction = QAction(QIcon('/usr/share/icons/onkyo_about.png'),"&About", self, triggered=self.about)
self.settingsAction = QAction(QIcon('/usr/share/icons/onkyo_settings.png'), "&Settings", self, triggered=self.config)
def createTrayIcon(self):
self.trayIconMenu = QMenu(self)
self.trayIconMenu.addAction(self.restoreAction)
self.trayIconMenu.addSeparator()
self.trayIconMenu.addAction(self.VolumeupAction)
self.trayIconMenu.addAction(self.VolumedownAction)
self.trayIconMenu.addAction(self.MuteAction)
self.trayIconMenu.addSeparator()
self.trayIconMenu.addAction(self.PoweroffAction)
self.trayIconMenu.addSeparator()
self.trayIconMenu.addAction(self.aboutAction)
self.trayIconMenu.addAction(self.quitAction)
self.trayIcon = QSystemTrayIcon(QIcon("/usr/share/icons/onkyo.png"), self)
self.trayIcon.setContextMenu(self.trayIconMenu)
def createMenu(self):
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(self.settingsAction)
fileMenu.addAction(self.quitAction)
helpMenu = menubar.addMenu('&Help')
helpMenu.addAction(self.aboutAction)
def sendTextToStatusBar(self, text):
self.statusBar().showMessage(str(text))
def createTrayError(self, e):
return self.trayIcon.showMessage('Error', 'Send command to receiver failed:\n' + str(e), QSystemTrayIcon.Critical, 5 * 1000)
def about(self):
title = self.tr("""<b>Onkyo QT</b>
<br/>License: GPLv3
<br/>Python {0} - on {1}""").format(platform.python_version(), platform.system())
image = ':/logo'
text = self.tr("""<p>Author: Andry Kondratiev <a href="mailto:[email protected]">[email protected]</a>
<p>Website: <a href="https://github.com/massdest/onkyoqtpy">
https://github.com/massdest/onkyoqtpy</a>
""")
contributors = QCoreApplication.translate("About dialog", """
Author: Andry Kondratiev<br/>
""", "List of contributors")
dialog = about_dlg.AboutDialog(title, text, image, contributors, self)
dialog.exec_()
def config(self):
dialog = settings.OnkyoSettings(self)
dialog.applied_signal.connect(self.config_save)
if dialog.exec_() == 1:
self.config_save()
def config_save(self):
logging.debug('Config saving...')
self.host = self.settings.value('host')
示例13: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
#.........这里部分代码省略.........
# print x
self.ui.serverList.addItem(x['name'])
def connect_handlers(self):
user_interface = self.ui
# Bind Add Events
user_interface.addButton.clicked.connect(self.handle_add_events)
user_interface.actionAdd_Server.triggered.connect(self.handle_add_events)
# Bind Edit Events
user_interface.editButton.clicked.connect(self.handle_edit_events)
# Bind Del Events
user_interface.delButton.clicked.connect(self.handle_del_events)
# Bind Toggle Events
user_interface.toggleButton.clicked.connect(self.handle_toggle_events)
user_interface.actionStart_Monitoring.triggered.connect(self.handle_toggle_events)
user_interface.actionStop_Monitoring.triggered.connect(self.handle_toggle_events)
# Bind Quit Events
user_interface.actionQuit.triggered.connect(self.handle_quit_events)
# Bind Signals
NOTIFIER.notify.connect(self.push_notifications)
def handle_add_events(self):
self.server_form.show()
self.hide()
def handle_edit_events(self):
try:
item = self.ui.serverList.selectedIndexes()[0]
index = item.row()
except:
index = None
if index is not None:
self.server_form.set_entry_id(index)
else:
self.server_form.set_default_texts()
self.server_form.show()
self.hide()
def handle_del_events(self):
try:
item = self.ui.serverList.selectedIndexes()[0]
index = item.row()
del self.data[index]
except:
pass
self.update_list()
self.refresh_list()
def handle_toggle_events(self):
try:
timer = self.timer
self.timer.cancel()
del self.timer
self.ui.toggleButton.setText("START")
self.ui.actionStop_Monitoring.setDisabled(True)
self.ui.actionStart_Monitoring.setEnabled(True)
self.systray_icon.showMessage('STOP', "Server monitoring was stopped!", self.msgIcon)
except:
self.ui.actionStop_Monitoring.setEnabled(True)
self.ui.actionStart_Monitoring.setDisabled(True)
self.ui.toggleButton.setText("STOP")
self.handle_timed_loop()
self.systray_icon.showMessage('START', "Server monitoring has started!", self.msgIcon)
def handle_quit_events(self):
self.timer.cancel()
self.close()
def handle_timed_loop(self):
self.notifications = monitor_servers(self.data)
self.timer = threading.Timer(10, self.handle_timed_loop)
self.timer.start()
NOTIFIER.notify.emit()
def push_notifications(self):
# print "ok- called"
for x in self.notifications:
self.systray_icon.showMessage('ALERT', x, self.msgIcon)
# pass
def closeEvent(self, event):
try:
timer = self.timer
self.timer.cancel()
del self.timer
except:
pass
event.accept()
示例14: Sansimera
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
#.........这里部分代码省略.........
else:
return
def refresh(self):
try:
if self.workThread.isRunning():
return
except AttributeError:
pass
self.menu.hide()
self.browser.clear()
self.lista = []
self.systray.setToolTip('Σαν σήμερα...')
self.browser.append('Λήψη...')
self.tentatives = 0
self.eortazontes_shown = False
self.download()
def activate(self, reason):
self.menu.hide()
state = self.isVisible()
if reason == 3:
if state:
self.hide()
return
else:
self.show()
return
if reason == 1:
self.menu.hide()
self.menu.popup(QCursor.pos())
def download(self):
self.workThread = WorkThread()
self.workThread.online_signal[bool].connect(self.status)
self.workThread.finished.connect(self.window)
self.workThread.event['QString'].connect(self.addlist)
self.workThread.names['QString'].connect(self.nameintooltip)
self.workThread.start()
def addlist(self, text):
self.lista.append(text)
def status(self, status):
self.status_online = status
def reminder_tray(self):
text = self.eortazontes_names.replace('<br/>', '\n')
urltexts = re.findall('(<a [\S]+php">)', text)
urltexts.extend(['</a>', '<p>', '<div>'])
show_notifier_text = text
for i in urltexts:
show_notifier_text = show_notifier_text.replace(i, '')
show_notifier_text = show_notifier_text.replace('\n\n', '\n')
show_notifier_text = show_notifier_text.replace('www.eortologio.gr)', 'www.eortologio.gr)\n')
self.systray.showMessage('Εορτάζουν:\n', show_notifier_text)
self.systray.setToolTip('Εορτάζουν:\n' + show_notifier_text)
def nameintooltip(self, text):
self.eortazontes_names = text
for i in ['<br/>', '<div>']:
text = text.replace(i, '')
self.eortazontes_in_window = text
if self.eortazontes_shown:
return
self.reminder_tray()
self.eortazontes_shown = True
def window(self):
self.lista.append('<div class=""></div>' + self.eortazontes_in_window)
if self.status_online:
self.browser.clear()
self.browser.append(self.lista[0])
self.lista_pos = 0
return
else:
if self.tentatives == 10:
return
self.timer.singleShot(5000, self.refresh)
self.tentatives += 1
def closeEvent(self, event):
self.settings.setValue("MainWindow/State", self.saveState())
def about(self):
self.menu.hide()
QMessageBox.about(self, "Εφαρμογή «Σαν σήμερα...»",
"""<b>sansimera-qt</b> v{0}
<p>Δημήτριος Γλενταδάκης <a href="mailto:[email protected]">[email protected]</a>
<br/>Ιστοσελίδα: <a href="https://github.com/dglent/sansimera-qt">
github sansimera-qt</a>
<p>Εφαρμογή πλαισίου συστήματος για την προβολή
<br/>των γεγονότων από την ιστοσελίδα <a href="http://www.sansimera.gr">
www.sansimera.gr</a><br/>
Πηγή εορτολογίου: <a href="http://www.eortologio.gr">
www.eortologio.gr</a>, <a href="http://www.synaxari.gr">
www.synaxari.gr</a>
<p>Άδεια χρήσης: GPLv3 <br/>Python {1} - Qt {2} - PyQt {3} σε {4}""".format(
__version__, platform.python_version(),
QT_VERSION_STR, PYQT_VERSION_STR, platform.system()))
示例15: NetDotTsinghuaApplication
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import showMessage [as 别名]
#.........这里部分代码省略.........
return super().exec()
def refresh_status(self):
logging.debug('Refreshing status in the menu')
s = STATUS_STR[self.status]
# Show session usage if possible.
if self.last_session and self.status in ('ONLINE',
'OTHERS_ACCOUNT_ONLINE'):
s = s + ' - ' + _usage_str(self.last_session.byte)
self.status_action.setText(s)
def refresh_username(self, username):
logging.debug('Refreshing username in the menu')
if not username:
self.username_action.setText('未设置账号')
self.usage_action.setVisible(False)
self.balance_action.setVisible(False)
else:
self.username_action.setText(username)
self.usage_action.setVisible(True)
self.balance_action.setVisible(True)
def refresh_account_info(self, balance, byte):
logging.debug('Refreshing account info section in the menu')
self.usage_action.setText('本月流量:{}'.format(_usage_str(byte)))
self.balance_action.setText('当前余额:{}'.format(_balance_str(balance)))
def status_changed(self, status):
# Show tray message.
if status == 'ONLINE':
self.tray.showMessage('当前在线', '本人账号在线')
elif status == 'OTHERS_ACCOUNT_ONLINE':
self.tray.showMessage('当前在线', '他人账号在线')
elif status == 'OFFLINE':
self.tray.showMessage('当前离线', '可以登录校园网')
self.status = status
def last_session_changed(self, session):
self.last_session = session
def refresh_sessions(self, sessions):
logging.debug('Refreshing sessions section in the menu')
self.sessions = sessions
self.last_check = datetime.now()
if len(sessions):
self.sessions_title_action.setText('当前在线')
else:
self.sessions_title_action.setText('无设备在线')
# Remove old actions
for menu in self.session_menus:
self.tray_menu.removeAction(menu.menuAction())
self.session_menus.clear()
# Add new actions.
for session in sessions:
menu = SessionMenu(self.worker.account, session)
self.tray_menu.insertMenu(self.last_check_action,
menu).setText(session.device_name)
self.session_menus.append(menu)