本文整理汇总了Python中PyQt5.QtWidgets.QSystemTrayIcon.setToolTip方法的典型用法代码示例。如果您正苦于以下问题:Python QSystemTrayIcon.setToolTip方法的具体用法?Python QSystemTrayIcon.setToolTip怎么用?Python QSystemTrayIcon.setToolTip使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QSystemTrayIcon
的用法示例。
在下文中一共展示了QSystemTrayIcon.setToolTip方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MyApp
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [as 别名]
class MyApp(QtWidgets.QMainWindow):
mouseLeaveTimer=0
def __init__(self):
# Ui_MainWindow.__init__(self)
#自己有__init__函数时,不会默认调用基类的__init__函数
# 因为这里重写了__init__将基类的覆盖掉了,故需要主动调用之
# QtWidgets.QMainWindow.__init__(self)
# super(MyApp,self).__init__()
#上面两句的作用是相同的,下面这句是python3的新写法
super().__init__()
# Get the Screen size
self.screenWidth=QDesktopWidget().availableGeometry().width()
self.screenHeight=QDesktopWidget().availableGeometry().height()
#初始化字体
font=QFont('黑体')
font.setPointSize(12)
app.setFont(font)
# ColorSetting
self.bgColor=QColor(66,66,77,88)
#
# self.setupUi(self)
self.initUI()
#用来控制半透明的bg面板自动消失
self.timer=QTimer()
self.timer.start(30)
self.setGeometry(0,30,self.screenWidth,self.screenHeight//3)
#Flagsq
self.IsMouseHover=False
self.MouseOver=False
self.Locked=False
self.Hidden=False
self.isDrag=False
self.isResize=False
#变量初始化
GLOBAL.WINDOWWIDTH=self.width()
GLOBAL.WINDOWHEIGHT=self.height()
self.bullets=[]
self.dragPos=QPoint(22,22)
self.savedName=''
# self.screenBuffer=QBitmap(GLOBAL.WINDOWWIDTH,GLOBAL.WINDOWHEIGHT)
# self.bufferPainter=QPainter(self.screenBuffer)
# self.picture=QPicture()
# 建立connection和slot的回调连接
self.createConnections()
# 连接到nodejs建立的服务器
self.connect2Server()
def initUI(self):
#构建托盘
self.trayIcon=QSystemTrayIcon(self)
self.trayIcon.setIcon(QtGui.QIcon("tmpIcon.ico"))
self.trayIcon.show()
self.trayIcon.setToolTip('BulletGo')
# 构建托盘菜单
action_quit=QAction('退出',self)
action_quit.triggered.connect(self.exitApp)
action_switchLock=QAction('锁定/解锁(F6)',self)
action_switchLock.triggered.connect(self.switchLock)
action_showHide=QAction('显示/隐藏(F7)',self)
action_showHide.triggered.connect(lambda:self.switchVisible(self))
action_Settings=QAction('设置',self)
action_Settings.triggered.connect(lambda:self.switchVisible(self.settingWindow))
trayIconMenu=QtWidgets.QMenu(self)
trayIconMenu.addAction(action_switchLock)
trayIconMenu.addAction(action_showHide)
trayIconMenu.addSeparator()
trayIconMenu.addAction(action_Settings)
trayIconMenu.addAction(action_quit)
#设定快捷键
QtWidgets.QShortcut(QtGui.QKeySequence(\
QtCore.Qt.Key_F7),self,\
(lambda:self.switchVisible(self.settingWindow)))
QtWidgets.QShortcut(QtGui.QKeySequence(\
QtCore.Qt.Key_F6),self,\
(self.switchLock))
self.trayIcon.setContextMenu(trayIconMenu)
# 保障不按下鼠标也追踪mouseMove事件
self.setMouseTracking(True)
self.setMinimumSize(600,260)
self.setWindowTitle("BulletGo")
sizeGrip=QtWidgets.QSizeGrip(self)
self.setWindowFlags(Qt.FramelessWindowHint\
|Qt.WindowStaysOnTopHint|Qt.Window|\
Qt.X11BypassWindowManagerHint)
#Plan A
self.setAttribute(Qt.WA_TranslucentBackground,True)
#这一句是给Mac系统用的,防止它绘制(很黯淡的)背景
self.setAutoFillBackground(False)
QSizeGrip(self).setVisible(True)
sizeGrip.setVisible(True)
#Plan B 失败
# palette=QPalette()
# color=QColor(190, 230, 250)
#.........这里部分代码省略.........
示例2: DemoImpl
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [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)
示例3: ZhaoChaFrame
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [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: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [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()
#.........这里部分代码省略.........
示例5: TrayIcon
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [as 别名]
#.........这里部分代码省略.........
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(
machine=_(self._machine),
state=_(self._machine_state),
)
if self._is_running:
output_state = _('output is enabled')
else:
output_state = _('output is disabled')
self._trayicon.setIcon(icon)
self._trayicon.setToolTip(
'Plover:\n- %s\n- %s' % (output_state, machine_state)
)
def _on_activated(self, reason):
if reason == QSystemTrayIcon.Trigger:
self.clicked.emit()
示例6: __init__
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [as 别名]
def __init__(self):
"""Init class."""
super(MainWindow, self).__init__()
self.statusBar().showMessage(getoutput(SYNCTHING + ' --version'))
self.setWindowTitle(__doc__.strip().capitalize())
self.setMinimumSize(640, 480)
self.setMaximumSize(1280, 1024)
self.resize(self.minimumSize())
self.setWindowIcon(QIcon.fromTheme("text-x-python"))
self.center()
self.view = QWebView(self)
self.view.loadFinished.connect(self.finishLoading)
self.view.page().linkHovered.connect(
lambda link_txt: self.statusBar().showMessage(link_txt[:99], 3000))
QShortcut("Ctrl++", self, activated=lambda:
self.view.setZoomFactor(self.view.zoomFactor() + 0.2))
QShortcut("Ctrl+-", self, activated=lambda:
self.view.setZoomFactor(self.view.zoomFactor() - 0.2))
QShortcut("Ctrl+0", self, activated=lambda: self.view.setZoomFactor(1))
QShortcut("Ctrl+q", self, activated=lambda: self.close())
self.menuBar().addMenu("File").addAction("Exit", lambda: self.close())
syncMenu = self.menuBar().addMenu("Sync")
syncMenu.addAction("Stop Syncronization", lambda: self.process.kill())
syncMenu.addAction("Start Syncronization", lambda: self.run())
viewMenu = self.menuBar().addMenu("View")
viewMenu.addAction(
"Zoom In",
lambda: self.view.setZoomFactor(self.view.zoomFactor() + .2))
viewMenu.addAction(
"Zoom Out",
lambda: self.view.setZoomFactor(self.view.zoomFactor() - .2))
viewMenu.addAction(
"Zoom To...", lambda: self.view.setZoomFactor(QInputDialog.getInt(
self, __doc__, "<b>Zoom factor ?:", 1, 1, 9)[0]))
viewMenu.addAction("Zoom Reset", lambda: self.view.setZoomFactor(1))
viewMenu.addSeparator()
viewMenu.addAction("Page Source", self.viewSource)
viewMenu.addAction("Open Web", lambda: open_new_tab(URL))
windowMenu = self.menuBar().addMenu("&Window")
windowMenu.addAction("Minimize", lambda: self.showMinimized())
windowMenu.addAction("Maximize", lambda: self.showMaximized())
windowMenu.addAction("Restore", lambda: self.showNormal())
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())
windowMenu.addAction("Fullscreen", lambda: self.showFullScreen())
windowMenu.addSeparator()
windowMenu.addAction("Increase size", lambda: self.resize(
self.size().width() * 1.2, self.size().height() * 1.2))
windowMenu.addAction("Decrease size", lambda: self.resize(
self.size().width() // 1.2, self.size().height() // 1.2))
windowMenu.addAction("Minimum size", lambda:
self.resize(self.minimumSize()))
windowMenu.addAction("Maximum size", lambda:
self.resize(self.maximumSize()))
windowMenu.addAction("Horizontal Wide", lambda: self.resize(
self.maximumSize().width(), self.minimumSize().height()))
windowMenu.addAction("Vertical Tall", lambda: self.resize(
self.minimumSize().width(), self.maximumSize().height()))
windowMenu.addSeparator()
windowMenu.addAction("Disable Resize",
lambda: self.setFixedSize(self.size()))
helpMenu = self.menuBar().addMenu("&Help")
helpMenu.addAction("Support Forum", lambda: open_new_tab(HELP_URL_0))
helpMenu.addAction("Lastest Release", lambda: open_new_tab(HELP_URL_1))
helpMenu.addAction("Documentation", lambda: open_new_tab(HELP_URL_2))
helpMenu.addAction("Bugs", lambda: open_new_tab(HELP_URL_3))
helpMenu.addAction("Source Code", lambda: open_new_tab(HELP_URL_4))
helpMenu.addSeparator()
helpMenu.addAction("About Qt 5", lambda: QMessageBox.aboutQt(self))
helpMenu.addAction("About Python 3",
lambda: open_new_tab('https://www.python.org'))
helpMenu.addAction("About" + __doc__,
lambda: QMessageBox.about(self, __doc__, HELPMSG))
helpMenu.addSeparator()
helpMenu.addAction("Keyboard Shortcuts", lambda:
QMessageBox.information(self, __doc__, SHORTCUTS))
helpMenu.addAction("View GitHub Repo", lambda: open_new_tab(__url__))
if not sys.platform.startswith("win"):
helpMenu.addAction("Show Source Code", lambda: call(
('xdg-open ' if sys.platform.startswith("linux") else 'open ')
+ __file__, shell=True))
helpMenu.addSeparator()
helpMenu.addAction("Check Updates", lambda: self.check_for_updates())
# process
self.process = QProcess()
self.process.error.connect(self._process_failed)
# backend options
self.chrt = QCheckBox("Smooth CPU ", checked=True)
self.ionice = QCheckBox("Smooth HDD ", checked=True)
self.chrt.setToolTip("Use Smooth CPUs priority (recommended)")
self.ionice.setToolTip("Use Smooth HDDs priority (recommended)")
self.chrt.setStatusTip(self.chrt.toolTip())
self.ionice.setStatusTip(self.ionice.toolTip())
# main toolbar
self.toolbar = self.addToolBar("SyncthinGUI Toolbar")
self.toolbar.addAction(QIcon.fromTheme("media-playback-stop"),
"Stop Sync", lambda: self.process.kill())
self.toolbar.addAction(QIcon.fromTheme("media-playback-start"),
"Restart Sync", lambda: self.run())
#.........这里部分代码省略.........
示例7: MainWidget
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [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",
#.........这里部分代码省略.........
示例8: MarksTimeTracker
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [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):
#.........这里部分代码省略.........
示例9: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [as 别名]
class MainWindow(Ui_MainWindow, QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
Ui_MainWindow.setupUi(self, self)
self.playlistDrop.dragEnterEvent = self.playlistDragEnterEvent
self.playlistDrop.dropEvent = self.playlistDropEvent
self.playlistModel = PlaylistModel()
self.playlistTable.setModel(self.playlistModel)
self.playlistTable.customContextMenuRequested.connect(self.playlistContextMenu)
self.playlistTable.doubleClicked.connect(self.onPlaylistDoubleClick)
self.playback = PlaybackWidget(self)
self.playbackLayout.addWidget(self.playback)
self.playback.playButton.clicked.connect(self.onPlaySelected)
self.playback.nextButton.clicked.connect(self.onNextClicked)
self.playback.prevButton.clicked.connect(self.onPrevClicked)
self.libraryDock.setTitleBarWidget(QWidget())
self.playlistsDock.setTitleBarWidget(QWidget())
self.toggleLibraryButton.clicked.connect(self.onToggleLibrary)
self.togglePlaylistsButton.clicked.connect(self.onTogglePlaylists)
self.library = LibraryWidget(self)
self.libraryDock.setWidget(self.library)
self.libraryDock.hide()
self.library.itemsActivated.connect(self.onLibraryItemActivated)
self.playlists = PlaylistsWidget(self)
self.playlistsDock.setWidget(self.playlists)
self.playlistsDock.hide()
self.playlists.loadPlaylist.connect(self.onPlaylistLoad)
self.dockState = 0
self.settings = QSettings('txplaya', 'txplaya')
if u'geometry/main' in self.settings.allKeys():
self.setGeometry(self.settings.value(u'geometry/main'))
for col in range(self.playlistModel.columnCount()):
width = self.settings.value(u'geometry/playlist/col/%d' % col)
self.playlistTable.setColumnWidth(col, int(width))
dockState = int(self.settings.value(u'geometry/dock/state'))
self.dockShow(dockState)
self.systemTray = QSystemTrayIcon(self.windowIcon())
self.systemTray.setToolTip('Playa')
self.systemTray.show()
self.systemTray.activated.connect(self.systemTrayToggle)
systemTrayMenu = QMenu()
systemTrayMenu.addAction(self.restore)
systemTrayMenu.addAction(self.quit)
self.systemTray.setContextMenu(systemTrayMenu)
self.restore.triggered.connect(self.restoreWindow)
self.quit.triggered.connect(self.quitEvent)
self.quitButton.clicked.connect(self.quitEvent)
self.quitFlag = False
# keyboard shortcuts
focusLibraryShortcut = QShortcut(QKeySequence('Ctrl+F'), self)
focusLibraryShortcut.activated.connect(self.onFocusLibrary)
deleteTrackShortcut = QShortcut(QKeySequence('Del'), self.playlistTable)
deleteTrackShortcut.setContext(Qt.WidgetShortcut)
deleteTrackShortcut.activated.connect(self.onDeleteTrack)
togglePlaybackShortcut = QShortcut(QKeySequence('Space'), self)
togglePlaybackShortcut.activated.connect(self.onTogglePlayback)
startShortcut = QShortcut(QKeySequence(Qt.Key_Return), self.playlistTable)
startShortcut.setContext(Qt.WidgetShortcut)
startShortcut.activated.connect(self.onPlaySelected)
undoShortcut = QShortcut(QKeySequence('Ctrl+Z'), self)
undoShortcut.activated.connect(self.onPlaylistUndo)
redoShortcut = QShortcut(QKeySequence('Ctrl+Shift+Z'), self)
redoShortcut.activated.connect(self.onPlaylistRedo)
saveShortcut = QShortcut(QKeySequence('Ctrl+S'), self)
saveShortcut.activated.connect(self.onPlaylistSave)
self.infoStreamStart()
QTimer.singleShot(200, self.fetchLibrary)
def infoStreamStart(self):
self.infoStream = QInfoStream()
self.infoStream.trackStarted.connect(self.playback.trackStarted)
self.infoStream.trackStarted.connect(self.playlistModel.trackActivated)
self.infoStream.playbackFinished.connect(self.playback.finished)
self.infoStream.playbackFinished.connect(self.playlistModel.trackActivated)
self.infoStream.playbackPaused.connect(self.playback.paused)
self.infoStream.playlistChanged.connect(self.onPlaylistChanged)
self.infoStream.disconnected.connect(self.reconnectDialog)
self.infoStream.timerUpdated.connect(self.playback.timerUpdated)
self.infoStream.playlistRegistryUpdated.connect(self.playlistRegistryUpdated)
def fetchLibrary(self):
from txplayagui.client import getLibrary
onHttpResponse(getLibrary(), self.onLibraryLoaded)
#.........这里部分代码省略.........
示例10: TriblerWindow
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [as 别名]
#.........这里部分代码省略.........
Dealing with low storage space available. First stop the downloads and the core manager and ask user to user to
make free space.
:return:
"""
self.downloads_page.stop_loading_downloads()
self.core_manager.stop(False)
close_dialog = ConfirmationDialog(self.window(), "<b>CRITICAL ERROR</b>",
"You are running low on disk space (<100MB). Please make sure to have "
"sufficient free space available and restart Tribler again.",
[("Close Tribler", BUTTON_TYPE_NORMAL)])
close_dialog.button_clicked.connect(lambda _: self.close_tribler())
close_dialog.show()
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()
示例11: MainApp
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [as 别名]
#.........这里部分代码省略.........
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more
details.</p>
<p>You should have received a copy of the GNU General Public
License along with this program. If not, see
<a href="https://www.gnu.org/licenses/gpl-3.0.html">
GNU General Public License version 3</a>.</p>""")
layout = QVBoxLayout()
titleLayout = QHBoxLayout()
titleLabel = QLabel('<font size="4"><b>{0} {1}</b></font>'.format('Webcam Manager', VERSION))
contentsLayout = QHBoxLayout()
aboutBrowser = QTextBrowser()
aboutBrowser.append(aboutText)
aboutBrowser.setOpenExternalLinks(True)
creditsBrowser = QTextBrowser()
creditsBrowser.append(creditsText)
creditsBrowser.setOpenExternalLinks(True)
licenseBrowser = QTextBrowser()
licenseBrowser.append(licenseText)
licenseBrowser.setOpenExternalLinks(True)
TabWidget = QTabWidget()
TabWidget.addTab(aboutBrowser, self.tr('About'))
TabWidget.addTab(creditsBrowser, self.tr('Contributors'))
TabWidget.addTab(licenseBrowser, self.tr('License'))
aboutBrowser.moveCursor(QTextCursor.Start)
creditsBrowser.moveCursor(QTextCursor.Start)
licenseBrowser.moveCursor(QTextCursor.Start)
icon = QIcon.fromTheme('camera-web')
pixmap = icon.pixmap(QSize(64, 64))
imageLabel = QLabel()
imageLabel.setPixmap(pixmap)
titleLayout.addWidget(imageLabel)
titleLayout.addWidget(titleLabel)
titleLayout.addStretch()
contentsLayout.addWidget(TabWidget)
buttonLayout = QHBoxLayout()
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
buttonLayout.addWidget(buttonBox)
layout.addLayout(titleLayout)
layout.addLayout(contentsLayout)
layout.addLayout(buttonLayout)
buttonBox.clicked.connect(dialog.accept)
dialog.setLayout(layout)
dialog.setMinimumSize(QSize(480, 400))
dialog.setWindowTitle(self.tr('About Webcam Manager'))
dialog.setWindowIcon(QIcon.fromTheme('help-about'))
dialog.show()
def enable(self):
tool = self.getGUISudo()
cmd = '%s modprobe -a uvcvideo' % tool
self.execCommand(cmd)
output = int(self.execCommand('lsmod | grep uvcvideo | wc -l').split()[0])
if output > 0:
self.updateTrayIcon(True)
self.showNotification('Webcam enabled!', 'Webcam is turned on and ready to use')
def disable(self):
tool = self.getGUISudo()
cmd = '%s modprobe -r uvcvideo' % tool
self.execCommand(cmd)
output = int(self.execCommand('lsmod | grep uvcvideo | wc -l').split()[0])
if output == 0:
self.updateTrayIcon(False)
self.showNotification('Webcam disabled!', 'Webcam is turned off')
def getGUISudo(self):
tools = ['kdesu', 'lxqt-sudo', 'gksu', 'gksudo', 'pkexec', 'sudo']
for tool in tools:
if distutils.spawn.find_executable(tool) is not None:
return tool
def execCommand(self, cmd):
try:
output = subprocess.check_output(cmd, shell=True)
return output
except subprocess.CalledProcessError as e:
self.showNotification('Error!', e.output)
def updateTrayIcon(self, active):
self.active = active
if self.active:
self.tray_icon.setIcon(QIcon.fromTheme('camera-on'))
self.tray_icon.setToolTip('Webcam is enabled')
else:
self.tray_icon.setIcon(QIcon.fromTheme('camera-off'))
self.tray_icon.setToolTip('Webcam is disabled')
def showNotification(self, title, message):
n = notify2.Notification(title, message, 'camera-web')
n.show()
示例12: Dialog
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [as 别名]
class Dialog(QDialog):
def __init__(self):
super().__init__()
# Создание парсера
self._dotaParser = parser.DotaParser()
# Инициализация GUI
self.initUi()
self.initTray()
self.initTimer()
# Первоначальный парсинг
self.startParser()
self.fillDialog()
def initUi(self):
self._ongoingTitle = QLabel("<h3>Ongoing matches</h3>")
self._ongoingLabel = QLabel("")
self._upcomingTitle = QLabel("<h3>Upcoming matches</h3>")
self._upcomingLabel = QLabel("")
self._quitButton = QPushButton("Quit")
self._layout = QVBoxLayout()
self._layout.addWidget(self._ongoingTitle)
self._layout.addWidget(self._ongoingLabel)
self._layout.addWidget(self._upcomingTitle)
self._layout.addWidget(self._upcomingLabel)
self._layout.addWidget(self._quitButton)
self.setLayout(self._layout)
self._quitButton.clicked.connect(qApp.quit)
self.setWindowTitle("Dota-2-Widget")
def initTray(self):
self._tray = QSystemTrayIcon()
self._tray.setToolTip("dota-2-widget")
self._tray.setIcon(QIcon("./dota2.gif"))
self._tray.activated.connect(self.showOrHideDialog)
self._tray.show()
def initTimer(self):
self._timer = QTimer()
self._timer.timeout.connect(self.startParser)
self._timer.timeout.connect(self.fillDialog)
self._timer.start(5000)
def startParser(self):
self._dotaParser.startParser()
#print("startParser")
def fillDialog(self):
# Получение результатов
ongoingMatches = self._dotaParser.getOngoingMatches()
upcomingMatches = self._dotaParser.getUpcomingMatches()
# Запись результатов
resultString = ""
for i in range(0, len(ongoingMatches)):
resultString += ongoingMatches[i] + '\n'
self._ongoingLabel.setText(resultString)
resultString = ""
for i in range(0, len(upcomingMatches)):
resultString += upcomingMatches[i] + '\n'
if (i > 10):
break
self._upcomingLabel.setText(resultString)
#print("fillDialog")
def closeEvent(self, ce):
if (self._tray.isVisible()):
self.hide()
def showOrHideDialog(self, result):
if (result == QSystemTrayIcon.Trigger):
if (not self.isVisible()):
self.show()
else:
self.hide()
示例13: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [as 别名]
#.........这里部分代码省略.........
widget = QWidget()
widget.setLayout(main_grid)
widget.setContentsMargins(10, 10, 10, 10)
self.setCentralWidget(widget)
# tray popup menu
if self.has_tray:
tray_popup = QMenu(self)
tray_popup.addAction(QIcon.fromTheme('dialog-password', QApplication.style().standardIcon(QStyle.SP_DriveHDIcon)), self.luks_device_name).setEnabled(False)
tray_popup.addSeparator()
self.tray_toggle_action = QAction(QApplication.style().standardIcon(QStyle. SP_DesktopIcon), _('Hide'), self)
self.tray_toggle_action.triggered.connect(self.toggle_main_window)
tray_popup.addAction(self.tray_toggle_action)
quit_action = QAction(QApplication.style().standardIcon(QStyle.SP_MessageBoxCritical), _('Quit'), self)
quit_action.triggered.connect(self.tray_quit)
tray_popup.addAction(quit_action)
# systray
self.tray = QSystemTrayIcon(self)
self.tray.setIcon(QIcon.fromTheme('dialog-password', QApplication.style().standardIcon(QStyle.SP_DriveHDIcon)))
self.tray.setContextMenu(tray_popup)
self.tray.activated.connect(self.toggle_main_window)
self.tray.show()
self.init_status()
def refresh(self):
""" Update widgets to reflect current container status. Adds systray icon if needed """
if self.is_unlocked:
self.label_status.setText(_('Container is {unlocked_green_bold}').format(
unlocked_green_bold='<font color="#006400"><b>' + _('unlocked') + '</b></font>'))
self.button_toggle_status.setText(_('Close Container'))
if self.has_tray:
self.tray.setToolTip(_('{device_name} is unlocked').format(device_name=self.luks_device_name))
else:
self.label_status.setText(_('Container is {closed_red_bold}').format(
closed_red_bold='<font color="#b22222"><b>' + _('closed') + '</b></font>'))
self.button_toggle_status.setText(_('Unlock Container'))
if self.has_tray:
self.tray.setToolTip(_('{device_name} is closed').format(device_name=self.luks_device_name))
self.show()
self.setFixedSize(self.sizeHint())
def tray_quit(self):
""" Triggered by clicking on `quit` in the systray popup: asks to close an unlocked container """
if not self.is_unlocked:
QApplication.instance().quit()
elif not self.is_waiting_for_worker:
self.show()
self.confirm_close()
def toggle_main_window(self, tray_icon_clicked):
""" Triggered by clicking on the systray icon: show/hide main window """
if not tray_icon_clicked or tray_icon_clicked == QSystemTrayIcon.Trigger: # don't activate on rightclick/contextmenu
if self.isVisible():
self.hide()
self.tray_toggle_action.setText(_('Show'))
else:
self.show()
self.tray_toggle_action.setText(_('Hide'))
def closeEvent(self, event):
""" Triggered by closing the window: If the container is unlocked, the program won't quit but remain in the systray. """
if not self.is_waiting_for_worker:
if self.is_unlocked:
示例14: __init__
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [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')
示例15: PymodoroGUI
# 需要导入模块: from PyQt5.QtWidgets import QSystemTrayIcon [as 别名]
# 或者: from PyQt5.QtWidgets.QSystemTrayIcon import setToolTip [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),
#.........这里部分代码省略.........