本文整理汇总了Python中PyQt5.QtWidgets.QSystemTrayIcon.setIcon方法的典型用法代码示例。如果您正苦于以下问题:Python QSystemTrayIcon.setIcon方法的具体用法?Python QSystemTrayIcon.setIcon怎么用?Python QSystemTrayIcon.setIcon使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QSystemTrayIcon
的用法示例。
在下文中一共展示了QSystemTrayIcon.setIcon方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Icon
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
class Icon(QWidget):
def __init__(self, app, newEntry, listWin):
super().__init__()
self.newEntry = newEntry
self.listWin = listWin
self.app = app
self.initUI()
def initUI(self):
menu = QMenu()
Ajouter = QAction(QIcon(''), '&Ajouter un tag', menu)
Ajouter.triggered.connect(self.newEntry.show)
menu.addAction(Ajouter)
ouvrir = QAction(QIcon(''), '&Ouvrir', menu)
ouvrir.triggered.connect(self.listWin.show)
menu.addAction(ouvrir)
Quitter = QAction(QIcon(''), '&Quitter', menu)
Quitter.triggered.connect(self.app.exit)
menu.addAction(Quitter)
self.icon = QSystemTrayIcon()
self.icon.setIcon(QIcon('./icone.png'))
self.icon.setContextMenu(menu)
self.icon.show()
示例2: Systray
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
class Systray(QObject):
trayIconMenu = None
def __init__(self, parent):
super().__init__(parent)
self.trayIconMenu = ContextMenu(None)
icon = QIcon(":/image/thunder.ico")
self.trayIcon = QSystemTrayIcon(self)
self.trayIcon.setIcon(icon)
self.trayIcon.setContextMenu(self.trayIconMenu)
self.trayIcon.setVisible(True)
self.trayIcon.activated.connect(self.slotSystrayActivated)
@pyqtSlot(QSystemTrayIcon.ActivationReason)
def slotSystrayActivated(self, reason):
if reason == QSystemTrayIcon.Context: # right
pass
elif reason == QSystemTrayIcon.MiddleClick: # middle
pass
elif reason == QSystemTrayIcon.DoubleClick: # double click
pass
elif reason == QSystemTrayIcon.Trigger: # left
if app.mainWin.isHidden() or app.mainWin.isMinimized():
app.mainWin.restore()
else:
app.mainWin.minimize()
示例3: _createTray
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
def _createTray(self):
from PyQt5.QtWidgets import QSystemTrayIcon
from PyQt5.QtGui import QIcon
from piony.common.system import expand_pj
tray = QSystemTrayIcon()
tray.setIcon(QIcon(expand_pj(":/res/tray-normal.png")))
tray.show()
return tray
示例4: Systray
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
class Systray(QObject):
app = None
trayIconMenu = None
def __init__(self, app):
super().__init__()
self.app = app
self.mainWin = self.app.mainWin
self.trayIconMenu = QMenu(None)
icon = QIcon(":/image/thunder.ico")
self.trayIcon = QSystemTrayIcon(None)
self.trayIcon.setIcon(icon)
self.trayIcon.setContextMenu(self.trayIconMenu)
self.trayIcon.setVisible(True)
self.trayIcon.activated.connect(self.slotSystrayActivated)
self.app.lastWindowClosed.connect(self.slotTeardown)
self.trayIconMenu.addAction(self.mainWin.action_exit)
@pyqtSlot()
def slotTeardown(self):
print("teardown Systray")
# On Ubuntu 13.10, systrayicon won't destroy itself gracefully, stops the whole program from exiting.
del self.trayIcon
@pyqtSlot(QSystemTrayIcon.ActivationReason)
def slotSystrayActivated(self, reason):
if reason == QSystemTrayIcon.Context: # right
pass
elif reason == QSystemTrayIcon.MiddleClick: # middle
pass
elif reason == QSystemTrayIcon.DoubleClick: # double click
pass
elif reason == QSystemTrayIcon.Trigger: # left
if self.mainWin.isHidden() or self.mainWin.isMinimized():
self.mainWin.restore()
else:
self.mainWin.minimize()
示例5: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
class MainWindow(QMainWindow):
"""Voice Changer main window."""
def __init__(self, parent=None):
super(MainWindow, self).__init__()
self.statusBar().showMessage("Move Dial to Deform Microphone Voice !.")
self.setWindowTitle(__doc__)
self.setMinimumSize(240, 240)
self.setMaximumSize(480, 480)
self.resize(self.minimumSize())
self.setWindowIcon(QIcon.fromTheme("audio-input-microphone"))
self.tray = QSystemTrayIcon(self)
self.center()
QShortcut("Ctrl+q", self, activated=lambda: self.close())
self.menuBar().addMenu("&File").addAction("Quit", lambda: exit())
self.menuBar().addMenu("Sound").addAction(
"STOP !", lambda: call('killall rec', shell=True))
windowMenu = self.menuBar().addMenu("&Window")
windowMenu.addAction("Hide", lambda: self.hide())
windowMenu.addAction("Minimize", lambda: self.showMinimized())
windowMenu.addAction("Maximize", lambda: self.showMaximized())
windowMenu.addAction("Restore", lambda: self.showNormal())
windowMenu.addAction("FullScreen", lambda: self.showFullScreen())
windowMenu.addAction("Center", lambda: self.center())
windowMenu.addAction("Top-Left", lambda: self.move(0, 0))
windowMenu.addAction("To Mouse", lambda: self.move_to_mouse_position())
# widgets
group0 = QGroupBox("Voice Deformation")
self.setCentralWidget(group0)
self.process = QProcess(self)
self.process.error.connect(
lambda: self.statusBar().showMessage("Info: Process Killed", 5000))
self.control = QDial()
self.control.setRange(-10, 20)
self.control.setSingleStep(5)
self.control.setValue(0)
self.control.setCursor(QCursor(Qt.OpenHandCursor))
self.control.sliderPressed.connect(
lambda: self.control.setCursor(QCursor(Qt.ClosedHandCursor)))
self.control.sliderReleased.connect(
lambda: self.control.setCursor(QCursor(Qt.OpenHandCursor)))
self.control.valueChanged.connect(
lambda: self.control.setToolTip(f"<b>{self.control.value()}"))
self.control.valueChanged.connect(
lambda: self.statusBar().showMessage(
f"Voice deformation: {self.control.value()}", 5000))
self.control.valueChanged.connect(self.run)
self.control.valueChanged.connect(lambda: self.process.kill())
# Graphic effect
self.glow = QGraphicsDropShadowEffect(self)
self.glow.setOffset(0)
self.glow.setBlurRadius(99)
self.glow.setColor(QColor(99, 255, 255))
self.control.setGraphicsEffect(self.glow)
self.glow.setEnabled(False)
# Timer to start
self.slider_timer = QTimer(self)
self.slider_timer.setSingleShot(True)
self.slider_timer.timeout.connect(self.on_slider_timer_timeout)
# an icon and set focus
QLabel(self.control).setPixmap(
QIcon.fromTheme("audio-input-microphone").pixmap(32))
self.control.setFocus()
QVBoxLayout(group0).addWidget(self.control)
self.menu = QMenu(__doc__)
self.menu.addAction(__doc__).setDisabled(True)
self.menu.setIcon(self.windowIcon())
self.menu.addSeparator()
self.menu.addAction(
"Show / Hide",
lambda: self.hide() if self.isVisible() else self.showNormal())
self.menu.addAction("STOP !", lambda: call('killall rec', shell=True))
self.menu.addSeparator()
self.menu.addAction("Quit", lambda: exit())
self.tray.setContextMenu(self.menu)
self.make_trayicon()
def run(self):
"""Run/Stop the QTimer."""
if self.slider_timer.isActive():
self.slider_timer.stop()
self.glow.setEnabled(True)
call('killall rec ; killall play', shell=True)
self.slider_timer.start(3000)
def on_slider_timer_timeout(self):
"""Run subprocess to deform voice."""
self.glow.setEnabled(False)
value = int(self.control.value()) * 100
command = f'play -q -V0 "|rec -q -V0 -n -d -R riaa bend pitch {value} "'
print(f"Voice Deformation Value: {value}")
print(f"Voice Deformation Command: {command}")
self.process.start(command)
if self.isVisible():
self.statusBar().showMessage("Minimizing to System TrayIcon", 3000)
print("Minimizing Main Window to System TrayIcon now...")
sleep(3)
self.hide()
#.........这里部分代码省略.........
示例6: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
class MainWindow(BaseWindow):
__contextName__ = 'MainWindow'
windowFocusChanged = pyqtSignal('QWindow*', arguments=['window'])
mousePressed = pyqtSignal('QPointF', arguments=['point'])
wheel = pyqtSignal('QPointF', arguments=['point'])
@registerContext
def __init__(self, engine=None, parent=None):
super(MainWindow, self).__init__(engine, parent)
self._initSystemTray()
self._initConnect()
def _initConnect(self):
from PyQt5.QtWidgets import qApp
qApp.focusWindowChanged.connect(self.changeFocusWindow)
signalManager.hideShowWindowToggle.connect(self.actionhideShow)
def _initSystemTray(self):
from PyQt5.QtWidgets import qApp
self.systemTray = QSystemTrayIcon(self)
self.systemTray.setIcon(qApp.windowIcon())
self.systemTray.show()
self.systemTray.activated.connect(self.onSystemTrayIconClicked)
def onSystemTrayIconClicked(self, reason):
if reason == QSystemTrayIcon.Unknown:
pass
elif reason == QSystemTrayIcon.Context:
menuWorker.systemTrayMenuShowed.emit()
elif reason == QSystemTrayIcon.DoubleClick:
pass
elif reason == QSystemTrayIcon.Trigger:
self.setVisible(not self.isVisible())
elif reason == QSystemTrayIcon.MiddleClick:
pass
else:
pass
def mousePressEvent(self, event):
self.mousePressed.emit(event.pos())
# 鼠标点击事件
if event.button() == Qt.LeftButton:
flag = windowManageWorker.windowMode
if flag == "Full":
x = self.quickItems['mainTitleBar'].x()
y = self.quickItems['mainTitleBar'].y()
width = self.quickItems['mainTitleBar'].width()
height = self.quickItems['mainTitleBar'].height()
rect = QRect(x, y, width, height)
if rect.contains(event.pos()):
self.dragPosition = event.globalPos() - \
self.frameGeometry().topLeft()
elif flag == "Simple":
x = self.rootObject().x()
y = self.rootObject().y()
width = self.rootObject().width()
height = 40
rect = QRect(x, y, width, height)
if rect.contains(event.pos()):
self.dragPosition = event.globalPos() - \
self.frameGeometry().topLeft()
super(MainWindow, self).mousePressEvent(event)
def changeFocusWindow(self, window):
self.windowFocusChanged.emit(window)
def wheelEvent(self, event):
self.wheel.emit(QPointF(event.x(), event.y()))
super(MainWindow, self).wheelEvent(event)
def keyPressEvent(self, event):
from controllers import configWorker, signalManager, mediaPlayer
if configWorker.isShortcutEnable:
modifier = QKeySequence(event.modifiers()).toString()
keyString = QKeySequence(event.key()).toString()
shortcut = modifier + keyString
print shortcut
if shortcut == configWorker.shortcut_preivous:
signalManager.previousSong.emit()
elif shortcut == configWorker.shortcut_next:
signalManager.nextSong.emit()
elif shortcut == configWorker.shortcut_volumnIncrease:
signalManager.volumnIncrease.emit()
elif shortcut == configWorker.shortcut_volumeDecrease:
signalManager.volumnDecrease.emit()
elif shortcut == configWorker.shortcut_playPause:
signalManager.playToggle.emit(not mediaPlayer.playing)
elif shortcut == configWorker.shortcut_simpleFullMode:
signalManager.simpleFullToggle.emit()
elif shortcut == configWorker.shortcut_miniFullMode:
signalManager.miniFullToggle.emit()
elif shortcut == configWorker.shortcut_hideShowWindow:
signalManager.hideShowWindowToggle.emit()
elif shortcut == configWorker.shortcut_hideShowDesktopLRC:
signalManager.hideShowDesktopLrcToggle.emit()
super(MainWindow, self).keyPressEvent(event)
#.........这里部分代码省略.........
示例7: SystemTrayIcon
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
class SystemTrayIcon(QMainWindow):
def __init__(self, parent=None):
super(SystemTrayIcon, self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.settings = QSettings()
self.language = self.settings.value('Language') or ''
self.temp_decimal_bool = self.settings.value('Decimal') or False
# initialize the tray icon type in case of first run: issue#42
self.tray_type = self.settings.value('TrayType') or 'icon&temp'
cond = conditions.WeatherConditions()
self.temporary_city_status = False
self.conditions = cond.trans
self.clouds = cond.clouds
self.wind = cond.wind
self.wind_dir = cond.wind_direction
self.wind_codes = cond.wind_codes
self.inerror = False
self.tentatives = 0
self.baseurl = 'http://api.openweathermap.org/data/2.5/weather?id='
self.accurate_url = 'http://api.openweathermap.org/data/2.5/find?q='
self.forecast_url = ('http://api.openweathermap.org/data/2.5/forecast/'
'daily?id=')
self.day_forecast_url = ('http://api.openweathermap.org/data/2.5/'
'forecast?id=')
self.wIconUrl = 'http://openweathermap.org/img/w/'
apikey = self.settings.value('APPID') or ''
self.appid = '&APPID=' + apikey
self.forecast_icon_url = self.wIconUrl
self.timer = QTimer(self)
self.timer.timeout.connect(self.refresh)
self.menu = QMenu()
self.citiesMenu = QMenu(self.tr('Cities'))
self.tempCityAction = QAction(self.tr('&Temporary city'), self)
self.refreshAction = QAction(self.tr('&Update'), self)
self.settingsAction = QAction(self.tr('&Settings'), self)
self.aboutAction = QAction(self.tr('&About'), self)
self.exitAction = QAction(self.tr('Exit'), self)
self.exitAction.setIcon(QIcon(':/exit'))
self.aboutAction.setIcon(QIcon(':/info'))
self.refreshAction.setIcon(QIcon(':/refresh'))
self.settingsAction.setIcon(QIcon(':/configure'))
self.tempCityAction.setIcon(QIcon(':/tempcity'))
self.citiesMenu.setIcon(QIcon(':/bookmarks'))
self.menu.addAction(self.settingsAction)
self.menu.addAction(self.refreshAction)
self.menu.addMenu(self.citiesMenu)
self.menu.addAction(self.tempCityAction)
self.menu.addAction(self.aboutAction)
self.menu.addAction(self.exitAction)
self.settingsAction.triggered.connect(self.config)
self.exitAction.triggered.connect(qApp.quit)
self.refreshAction.triggered.connect(self.manual_refresh)
self.aboutAction.triggered.connect(self.about)
self.tempCityAction.triggered.connect(self.tempcity)
self.systray = QSystemTrayIcon()
self.systray.setContextMenu(self.menu)
self.systray.activated.connect(self.activate)
self.systray.setIcon(QIcon(':/noicon'))
self.systray.setToolTip(self.tr('Searching weather data...'))
self.notification = ''
self.notification_temp = 0
self.notifications_id = ''
self.systray.show()
# The dictionnary has to be intialized here. If there is an error
# the program couldn't become functionnal if the dictionnary is
# reinitialized in the weatherdata method
self.weatherDataDico = {}
# The traycolor has to be initialized here for the case when we cannot
# reach the tray method (case: set the color at first time usage)
self.traycolor = ''
self.refresh()
def icon_loading(self):
self.gif_loading = QMovie(":/loading")
self.gif_loading.frameChanged.connect(self.update_gif)
self.gif_loading.start()
def update_gif(self):
gif_frame = self.gif_loading.currentPixmap()
self.systray.setIcon(QIcon(gif_frame))
def manual_refresh(self):
self.tentatives = 0
self.refresh()
def cities_menu(self):
# Don't add the temporary city in the list
if self.temporary_city_status:
return
self.citiesMenu.clear()
cities = self.settings.value('CityList') or []
if type(cities) is str:
cities = eval(cities)
try:
current_city = (self.settings.value('City') + '_' +
self.settings.value('Country') + '_' +
self.settings.value('ID'))
except:
# firsttime run,if clic cancel in setings without any city configured
pass
#.........这里部分代码省略.........
示例8: TrayIcon
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
class TrayIcon(QObject):
def __init__(self):
super().__init__()
self._supported = QSystemTrayIcon.isSystemTrayAvailable()
self._context_menu = None
self._enabled = False
self._trayicon = None
self._state_icons = {}
for state in (
'disconnected',
'disabled',
'enabled',
):
icon = QIcon(':/state-%s.svg' % state)
if hasattr(icon, 'setIsMask'):
icon.setIsMask(True)
self._state_icons[state] = icon
self._machine = None
self._machine_state = 'disconnected'
self._is_running = False
self._update_state()
def set_menu(self, menu):
self._context_menu = menu
if self._enabled:
self._trayicon.setContextMenu(menu)
def log(self, level, message):
if self._enabled:
if level <= log.INFO:
icon = QSystemTrayIcon.Information
timeout = 10
elif level <= log.WARNING:
icon = QSystemTrayIcon.Warning
timeout = 15
else:
icon = QSystemTrayIcon.Critical
timeout = 25
self._trayicon.showMessage(__software_name__.capitalize(),
message, icon, timeout * 1000)
else:
if level <= log.INFO:
icon = QMessageBox.Information
elif level <= log.WARNING:
icon = QMessageBox.Warning
else:
icon = QMessageBox.Critical
msgbox = QMessageBox()
msgbox.setText(message)
msgbox.setIcon(icon)
msgbox.exec_()
def is_supported(self):
return self._supported
def enable(self):
if not self._supported:
return
self._trayicon = QSystemTrayIcon()
# On OS X, the context menu is activated with either mouse buttons,
# and activation messages are still sent, so ignore those...
if not sys.platform.startswith('darwin'):
self._trayicon.activated.connect(self._on_activated)
if self._context_menu is not None:
self._trayicon.setContextMenu(self._context_menu)
self._enabled = True
self._update_state()
self._trayicon.show()
def disable(self):
if not self._enabled:
return
self._trayicon.hide()
self._trayicon = None
self._enabled = False
def is_enabled(self):
return self._enabled
def update_machine_state(self, machine, state):
self._machine = machine
self._machine_state = state
self._update_state()
def update_output(self, enabled):
self._is_running = enabled
self._update_state()
clicked = pyqtSignal()
def _update_state(self):
if self._machine_state not in ('initializing', 'connected'):
state = 'disconnected'
else:
state = 'enabled' if self._is_running else 'disabled'
icon = self._state_icons[state]
if not self._enabled:
return
machine_state = _('{machine} is {state}').format(
#.........这里部分代码省略.........
示例9: Coropata
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
#.........这里部分代码省略.........
Qt.BypassWindowManagerHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.m_hoverbox = Hoverbox()
self.m_hoverbox.show()
self.m_animation_timer = QTimer(self)
self.m_animation_timer.setInterval(100)
self.m_physics_timer = QTimer(self)
self.m_physics_timer.setInterval(30)
self.m_physics_timer.timeout.connect(self.physicsTimerEvent)
self.screen_width = QDesktopWidget().screenGeometry().width()
self.screen_height = QDesktopWidget().screenGeometry().height()
# Initialize properties
self.m_velocity = QPoint(0, 0)
self.m_pos = QPoint(self.screen_width / 2, (5.0 / 6.0) * self.screen_height)
self.m_offset = QPoint(0, 0)
self.m_size = QSize(0, 0)
self._velocity = self.m_velocity
self._pos = self.m_pos
self._offset = self.m_offset
self._size = self.m_size
self.stateMachine = xmlToStateMachine(self, 'coropata.xml')
self.stateMachine.start()
self.m_animation_timer.start()
self.m_physics_timer.start()
# Properties ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@pyqtProperty(QSize)
def _size(self):
return self.m_size
@_size.write
def _size(self, value):
self.m_size = value
self.setFixedSize(value)
@pyqtProperty(QPoint)
def _offset(self):
return self.m_offset
@_offset.write
def _offset(self, value):
self.m_offset = value
self.move(self.m_pos + self.m_offset)
@pyqtProperty(QPoint)
def _pos(self):
return self.m_pos
@_pos.write
def _pos(self, value):
self.m_pos = value
self.move(self.m_pos + self.m_offset)
self.m_hoverbox.move(self.m_pos - QPoint(60, 70))
@pyqtProperty(QPoint)
def _velocity(self):
return self.m_velocity
@_velocity.write
def _velocity(self, value):
self.m_velocity = value
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def mousePressEvent(self, e):
self.clicked.emit()
def closeEvent(self, e):
QApplication.instance().closeAllWindows()
def keyPressEvent(self, e):
if e.key() == Qt.Key_Q or e.key() == Qt.Key_Escape:
QApplication.instance().closeAllWindows()
def physicsTimerEvent(self):
p = self.m_pos + self.m_velocity
if p.x() < -self._size.width():
p.setX(self.screen_width)
elif p.x() > self.screen_width + 10:
p.setX(-self._size.width())
self._pos = p
def createTrayIcon(self):
self.quitAction = QAction('Quit', self)
self.quitAction.triggered.connect(self.closeEvent)
self.trayIconMenu = QMenu(self)
self.trayIconMenu.addAction(self.quitAction)
self.trayIcon = QSystemTrayIcon(self)
self.trayIcon.setContextMenu(self.trayIconMenu)
self.trayIcon.setIcon(QIcon(os.path.join('images', 'flower.png')))
self.trayIcon.show()
示例10: MarksTimeTracker
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
class MarksTimeTracker(QMainWindow, Ui_MainWindow):
runningEvent = None
def __init__(self, parent=None):
super(MarksTimeTracker, self).__init__(parent)
self.setupUi(self)
self.tabWidget.tabBar().hide()
self.setupStatusIcon()
# config
self.config_path = os.path.join(os.path.expanduser('~'), '.config', 'markstimetracker')
dir_util.mkpath(self.config_path)
self.readConfig()
# Setup DB
engine = create_engine('sqlite:///' + os.path.join(self.config_path, 'markstimetracker.db'))
init_db(engine)
self.db = sessionmaker(bind=engine)()
self.updateTaskList()
self.updateTasksComboBox()
self.checkForRunningTask()
# Timers
timer = QTimer(self)
timer.timeout.connect(self.updateTimeSpent)
timer.start(1000)
self.idleTimeTimer = QTimer()
self.idleTimeTimer.timeout.connect(self.detectIdleTime)
self.checkIdleTime()
self.remindTimer = QTimer()
self.remindTimer.timeout.connect(self.remindTracking)
self.checkRemind()
self.redmineSyncTimer = QTimer()
self.redmineSyncTimer.timeout.connect(self.doRedmineSync)
self.checkRedmineSync()
# Events
self.startButton.clicked.connect(self.toggleEventButton)
self.eventsPeriodComboBox.currentIndexChanged.connect(self.eventsPeriodChanged)
self.editDurationSpinBox.valueChanged.connect(self.updateEditStartEndTime)
self.editStartDateTimeEdit.dateTimeChanged.connect(self.updateDurationSpinBoxEndTime)
self.editEndDateTimeEdit.dateTimeChanged.connect(self.updateDurationSpinBox)
self.editButtonBox.accepted.connect(self.saveEvent)
self.editButtonBox.rejected.connect(lambda: self.tabWidget.setCurrentIndex(TAB_MAIN))
self.settingsButtonBox.accepted.connect(self.saveSettings)
self.settingsButtonBox.rejected.connect(lambda: self.tabWidget.setCurrentIndex(TAB_MAIN))
self.settingsPushButton.clicked.connect(
lambda: self.tabWidget.setCurrentIndex(TAB_SETTINGS))
self.redmineSyncPushButton.clicked.connect(lambda: self.doRedmineSync(check=False))
self.addEventPushButton.clicked.connect(self.addEvent)
self.setupDbus()
def setupStatusIcon(self):
icon = QIcon()
icon.addPixmap(QPixmap(":/clock.svg"), QIcon.Normal, QIcon.Off)
self.statusIcon = QSystemTrayIcon(self)
self.statusIcon.setIcon(icon)
self.statusIcon.activated.connect(lambda: self.hide()
if self.isVisible()
else self.show())
self.statusIcon.setToolTip("Mark's Time Tracker")
self.statusIcon.show()
def setupDbus(self):
dbus_loop = DBusQtMainLoop(set_as_default=True)
self.bus = dbus.SessionBus(mainloop=dbus_loop)
signals = [('org.freedesktop.ScreenSaver', '/org/freedesktop/ScreenSaver', 'ActiveChanged'),
('com.canonical.Unity', '/com/canonical/Unity/Session', 'Locked')]
for org, path, event in signals:
screensaver = self.bus.get_object(org, path)
screensaver.connect_to_signal(event, self.checkLockScreen)
def updateTasksComboBox(self):
self.tasksComboBox.clear()
self.editTaskListComboBox.clear()
self.tasksComboBox.addItem('')
self.tasksComboBox.lineEdit().setPlaceholderText("What are you going to do?")
for task in self.db.query(Task).all():
if task.active:
self.tasksComboBox.addItem(task.description)
self.editTaskListComboBox.addItem(task.description)
def updateTimeSpent(self):
if self.runningEvent:
spent_time = self.runningEvent.spent_time
m, s = divmod(spent_time, 60)
h, m = divmod(m, 60)
self.timeLabel.setText("{h:02d}:{m:02d}:{s:02d}".format(h=h, m=m, s=s))
period = self.eventsPeriodComboBox.currentText()
start, end = self.getStartEndForPeriod(period)
total = Event.get_spent_time_period(self.db, start, end)
self.totalTimeLabel.setText("{}h".format(total))
def getStartEndForPeriod(self, period):
#.........这里部分代码省略.........
示例11: __init__
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
#.........这里部分代码省略.........
self.status_icon.hide()
self.status_icon = None
if not self.popup is None:
self.popup.deleteLater()
self.popup = None
self.qapp.processEvents()
def run(self):
self.status_icon.show()
self.timer.start(500)
logger.info("[qt4systrayicon] begin loop", self)
self.qapp.exec_()
logger.info("[qt4systrayicon] end loop", self)
self.prepairExit()
def updateInfo(self):
if not tools.processAlive(self.ppid):
self.prepairExit()
self.qapp.exit(0)
return
paused = tools.processPaused(self.snapshots.pid())
self.btnPause.setVisible(not paused)
self.btnResume.setVisible(paused)
message = self.snapshots.takeSnapshotMessage()
if message is None and self.last_message is None:
message = (0, _('Working...'))
if not message is None:
if message != self.last_message:
self.last_message = message
if self.decode:
message = (message[0], self.decode.log(message[1]))
self.menuStatusMessage.setText('\n'.join(tools.wrapLine(message[1],\
size = 80,\
delimiters = '',\
new_line_indicator = '') \
))
self.status_icon.setToolTip(message[1])
pg = progress.ProgressFile(self.config)
if pg.fileReadable():
pg.load()
percent = pg.intValue('percent')
if percent != self.progressBar.value():
self.progressBar.setValue(percent)
self.progressBar.render(self.pixmap, sourceRegion = QRegion(0, -14, 24, 6), flags = QWidget.RenderFlags(QWidget.DrawChildren))
self.status_icon.setIcon(QIcon(self.pixmap))
self.menuProgress.setText(' | '.join(self.getMenuProgress(pg)))
self.menuProgress.setVisible(True)
else:
self.status_icon.setIcon(self.icon.BIT_LOGO)
self.menuProgress.setVisible(False)
def getMenuProgress(self, pg):
d = (('sent', _('Sent:')), \
('speed', _('Speed:')),\
('eta', _('ETA:')))
for key, txt in d:
value = pg.strValue(key, '')
if not value:
continue
yield txt + ' ' + value
def onStartBIT(self):
profileID = self.config.currentProfile()
cmd = ['backintime-qt4',]
if not profileID == '1':
cmd += ['--profile-id', profileID]
proc = subprocess.Popen(cmd)
def onOpenLog(self):
dlg = logviewdialog.LogViewDialog(self, systray = True)
dlg.decode = self.decode
dlg.cbDecode.setChecked(self.btnDecode.isChecked())
dlg.exec_()
def onBtnDecode(self, checked):
if checked:
self.decode = encfstools.Decode(self.config)
self.last_message = None
self.updateInfo()
else:
self.decode = None
def onBtnStop(self):
os.kill(self.snapshots.pid(), signal.SIGKILL)
self.btnStop.setEnabled(False)
self.btnPause.setEnabled(False)
self.btnResume.setEnabled(False)
self.snapshots.setTakeSnapshotMessage(0, 'Snapshot terminated')
示例12: PymodoroGUI
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [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),
#.........这里部分代码省略.........
示例13: MainWidget
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
class MainWidget(QTabWidget):
"""Custom main widget."""
def __init__(self, parent=None, *args, **kwargs):
"""Init class custom tab widget."""
super(MainWidget, self).__init__(parent=None, *args, **kwargs)
self.parent = parent
self.setTabBar(TabBar(self))
self.setMovable(False)
self.setTabsClosable(False)
self.setTabShape(QTabWidget.Triangular)
self.init_preview()
self.init_corner_menus()
self.init_tray()
self.addTab(TabSearch(self), "Search")
self.addTab(TabTool(self), "Tools")
self.addTab(TabHtml(self), "HTML")
self.addTab(TabSymbols(self), "Symbols")
self._recent_tab = TabRecent(self)
self.recentify = self._recent_tab.recentify # shortcut
self.addTab(self._recent_tab, "Recent")
self.widgets_to_tabs(self.json_to_widgets(UNICODEMOTICONS))
self.make_trayicon()
self.setMinimumSize(QDesktopWidget().screenGeometry().width() // 1.5,
QDesktopWidget().screenGeometry().height() // 1.5)
# self.showMaximized()
def init_preview(self):
self.previews, self.timer = [], QTimer(self)
self.fader, self.previous_pic = FaderWidget(self), None
self.timer.setSingleShot(True)
self.timer.timeout.connect(lambda: [_.close() for _ in self.previews])
self.taimer, self.preview = QTimer(self), QLabel("Preview")
self.taimer.setSingleShot(True)
self.taimer.timeout.connect(lambda: self.preview.hide())
font = self.preview.font()
font.setPixelSize(100)
self.preview.setFont(font)
self.preview.setDisabled(True)
self.preview.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
self.preview.setAttribute(Qt.WA_TranslucentBackground, True)
def init_corner_menus(self):
self.menu_1, self.menu_0 = QToolButton(self), QToolButton(self)
self.menu_1.setText(" ⚙ ")
self.menu_1.setToolTip("<b>Options, Extras")
self.menu_0.setText(" ? ")
self.menu_0.setToolTip("<b>Help, Info")
font = self.menu_1.font()
font.setBold(True)
self.menu_1.setFont(font)
self.menu_0.setFont(font)
self.menu_tool, self.menu_help = QMenu("Tools Extras"), QMenu("Help")
self.menu_tool.addAction(" Tools & Extras ").setDisabled(True)
self.menu_help.addAction(" Help & Info ").setDisabled(True)
self.menu_0.setMenu(self.menu_help)
self.menu_1.setMenu(self.menu_tool)
self.menu_tool.addAction("Explain Unicode", self.make_explain_unicode)
self.menu_tool.addAction("Alternate Case Clipboard",
self.alternate_clipboard)
self.menu_tool.addSeparator()
self.menu_tool.addAction("AutoCenter Window", self.center)
self.menu_tool.addAction("Set Icon", self.set_icon)
self.menu_tool.addAction( # force recreate desktop file
"Add Launcher to Desktop", lambda: set_desktop_launcher(
"unicodemoticon", AUTOSTART_DESKTOP_FILE, True))
self.menu_tool.addAction("Move to Mouse position",
self.move_to_mouse_position)
self.menu_tool.addSeparator()
self.menu_tool.addAction("Minimize", self.showMinimized)
self.menu_tool.addAction("Hide", self.hide)
self.menu_tool.addAction("Quit", exit)
self.menu_help.addAction("About Qt 5",
lambda: QMessageBox.aboutQt(None))
self.menu_help.addAction("About Unicodemoticon",
lambda: open_new_tab(__url__))
self.setCornerWidget(self.menu_1, 1)
self.setCornerWidget(self.menu_0, 0)
self.currentChanged.connect(self.make_tabs_previews)
self.currentChanged.connect(self.make_tabs_fade)
def init_tray(self):
self.tray, self.menu = QSystemTrayIcon(self), QMenu(__doc__)
self.menu.addAction(" Emoticons").setDisabled(True)
self.menu.setIcon(self.windowIcon())
self.menu.addSeparator()
self.menu.setProperty("emoji_menu", True)
list_of_labels = sorted(UNICODEMOTICONS.keys()) # menus
menus = [self.menu.addMenu(_.title()) for _ in list_of_labels]
self.menu.addSeparator()
log.debug("Building Emoticons SubMenus.")
for item, label in zip(menus, list_of_labels):
item.setStyleSheet("padding:0;margin:0;border:0;menu-scrollable:1")
font = item.font()
font.setPixelSize(20)
item.setFont(font)
self.build_submenu(UNICODEMOTICONS[label.lower()], item)
self.menu.addSeparator()
self.menu.addAction("Alternate Case Clipboard",
#.........这里部分代码省略.........
示例14: Window
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [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)
#.........这里部分代码省略.........
示例15: SystemTray
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setIcon [as 别名]
class SystemTray(QDialog):
tray_alert_signal = pyqtSignal((str,))
def __init__(self):
super().__init__()
self.create_actions()
self.create_tray_icon()
self.containing_folder = ""
def create_actions(self):
# menu items
self.open_osf_folder_action = QAction("Open OSF Folder", self)
self.launch_osf_action = QAction("Launch OSF", self)
self.sync_now_action = QAction("Sync Now", self)
self.currently_synching_action = QAction("Up to date", self)
self.currently_synching_action.setDisabled(True)
self.preferences_action = QAction("Settings", self)
self.about_action = QAction("&About", self)
self.quit_action = QAction("&Quit", self)
def create_tray_icon(self):
self.tray_icon_menu = QMenu(self)
self.tray_icon_menu.addAction(self.open_osf_folder_action)
self.tray_icon_menu.addAction(self.launch_osf_action)
self.tray_icon_menu.addSeparator()
self.tray_icon_menu.addAction(self.sync_now_action)
self.tray_icon_menu.addAction(self.currently_synching_action)
self.tray_icon_menu.addSeparator()
self.tray_icon_menu.addAction(self.preferences_action)
self.tray_icon_menu.addAction(self.about_action)
self.tray_icon_menu.addSeparator()
self.tray_icon_menu.addAction(self.quit_action)
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setContextMenu(self.tray_icon_menu)
# todo: do we have a better icon for use with desktop apps?
icon = QIcon(":/cos_logo_backup.png")
self.tray_icon.setIcon(icon)
def start(self):
self.tray_icon.show()
def update_currently_synching(self, val):
self.currently_synching_action.setText(str(val))
self.tray_icon.show()
def set_containing_folder(self, new_containing_folder):
logging.debug("setting new containing folder is :{}".format(self.containing_folder))
self.containing_folder = new_containing_folder
def start_osf(self):
url = "http://osf.io"
webbrowser.open_new_tab(url)
def open_osf_folder(self):
# fixme: containing folder not being updated.
import logging
logging.debug("containing folder is :{}".format(self.containing_folder))
if validate_containing_folder(self.containing_folder):
if sys.platform == "win32":
os.startfile(self.containing_folder)
elif sys.platform == "darwin":
subprocess.Popen(["open", self.containing_folder])
else:
try:
subprocess.Popen(["xdg-open", self.containing_folder])
except OSError:
raise NotImplementedError
else:
AlertHandler.warn("osf folder is not set")