本文整理汇总了Python中PyQt4.QtGui.QSystemTrayIcon.setToolTip方法的典型用法代码示例。如果您正苦于以下问题:Python QSystemTrayIcon.setToolTip方法的具体用法?Python QSystemTrayIcon.setToolTip怎么用?Python QSystemTrayIcon.setToolTip使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtGui.QSystemTrayIcon
的用法示例。
在下文中一共展示了QSystemTrayIcon.setToolTip方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Tray
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
class Tray(QObject):
activated = pyqtSignal()
def __init__(self, parent, title, icon):
QObject.__init__(self)
# Setup contextual menu
if kde:
self.menu = KMenu(parent)
self.tray = KStatusNotifierItem(parent)
self.tray.setStatus(KStatusNotifierItem.Passive)
self.tray.setCategory(KStatusNotifierItem.ApplicationStatus)
self.tray.setAssociatedWidget(parent)
self.tray.setStandardActionsEnabled(False)
self.tray.activateRequested.connect(self._activateRequested)
else:
self.menu = QMenu()
self.tray = QSystemTrayIcon()
self.tray.activated.connect(self._activated)
self.setIcon(icon)
self.setTitle(title)
if not kde:
self.tray.show()
self.tray.setContextMenu(self.menu)
def setActive(self, active=True):
if kde:
self.tray.setStatus(KStatusNotifierItem.Active if active else KStatusNotifierItem.Passive)
def setTitle(self, title):
if kde:
self.tray.setTitle(title)
self.tray.setToolTipTitle(title)
else:
self.tray.setToolTip(title)
self.menu.setTitle(title)
def setToolTipSubTitle(self, subtitle):
if kde:
self.tray.setToolTipSubTitle(subtitle)
def setIcon(self, icon):
if kde:
self.tray.setIconByPixmap(icon)
self.tray.setToolTipIconByPixmap(icon)
else:
self.tray.setIcon(icon)
def showMessage(self, title, message, icon=None):
if kde:
self.tray.showMessage(title, message, "network-server")
else:
self.tray.showMessage(title, message, QSystemTrayIcon.Information if icon is None else icon)
def _activated(self, reason):
if reason == QSystemTrayIcon.DoubleClick:
self.activated.emit()
def _activateRequested(self, active, pos):
self.activated.emit()
示例2: WingedBox
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
class WingedBox(QWidget):
def __init__(self):
QWidget.__init__(self)
self.setWindowTitle('WingedBox')
pixmap = QPixmap(config.images['icon'])
self.setWindowIcon(QIcon(pixmap))
self.user = ''
self.password = ''
self._vbox = QVBoxLayout(self)
self._login = Login(self, HOME_WINGED_PATH)
self._vbox.addWidget(self._login)
self._winged = Winged(self, pref)
self._winged.setVisible(False)
self._vbox.addWidget(self._winged)
#SystemTray Menu
self._menu = QMenu('WingedBox')
self._myfiles = self._menu.addAction(QIcon(config.images['icon']), 'Files')
self._myfiles.setEnabled(False)
self._init = self._menu.addAction(self.style().standardIcon(QStyle.SP_DialogOkButton), 'Init Session')
self._close = self._menu.addAction(self.style().standardIcon(QStyle.SP_DialogCloseButton), 'Close Session')
self._close.setVisible(False)
self._menu.addSeparator()
self._properties = self._menu.addAction('Preferences')
self._menu.addSeparator()
exit = self._menu.addAction(self.style().standardIcon(QStyle.SP_TitleBarCloseButton), 'Exit')
#SystemTray
self._tray = QSystemTrayIcon(QIcon(pixmap), self)
self._tray.setToolTip('WingedBox')
self._tray.setVisible(True)
self._tray.setContextMenu(self._menu)
#Signal -> Slot
self.connect(exit, SIGNAL("triggered()"), sys.exit)
self.connect(self._myfiles, SIGNAL("triggered()"), self.show)
self.connect(self._init, SIGNAL("triggered()"), self.show)
self.connect(self._properties, SIGNAL("triggered()"), self.show_properties)
self.connect(self._close, SIGNAL("triggered()"), self.disconnect)
def show_properties(self):
self.prop = preferences.Preferences(self, pref)
self.prop.show()
def disconnect(self):
self.user = ''
self.password = ''
self._myfiles.setEnabled(False)
self._init.setVisible(True)
self._close.setVisible(False)
self._winged.hide()
self._login.show()
def closeEvent(self, event):
event.ignore()
self.hide()
示例3: StartQT4
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
class StartQT4(Windows):
def keyPressEvent(self, event):
k = event.key()
if k == QtCore.Qt.Key_Escape:
sys.exit()
elif k == QtCore.Qt.Key_Enter-1:
self.ui.btnSend.clicked.emit(True)
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_winMain()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.btnSend, QtCore.SIGNAL("clicked()"), self.SendQuery)
self.setMouseTracking(True)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint|QtCore.Qt.WindowStaysOnTopHint| Qt.Popup | Qt.Tool)
# 创建托盘
self.icon = QIcon("img.png")
self.trayIcon = QSystemTrayIcon(self)
self.trayIcon.setIcon(self.icon)
self.trayIcon.setToolTip(u"simple有道")
self.trayIcon.show()
# 托盘气泡消息
self.trayIcon.showMessage(u"simple有道", u"simple有道已经启动,随时待命!")
# 托盘菜单
self.action = QAction(u"退出simple有道", self, triggered = sys.exit) # 触发点击后调用sys.exit()命令,即退出
self.menu = QMenu(self)
self.menu.addAction(self.action)
self.trayIcon.setContextMenu(self.menu)
self.move(1100,50)
#开启监听线程
system("xclip -f /dev/null") #清空剪切板
listener = Thread(target=listenMouse, args=(self.ui,))
listener.setDaemon(True)
listener.start()
def SendQuery(self):
querystring = "http://fanyi.youdao.com/openapi.do?keyfrom=hustbg&key=1205943053&type=data&doctype=json&version=1.1&q="+unicode(self.ui.txtSend.text())
response = json.loads(requests.get(querystring).text)
try:
result = u" 音标:"+response["basic"].get("phonetic","")+u"\n 翻译:"+u','.join(response["translation"])+u"\n 解释:\n "+'\n '.join(response["basic"]["explains"][0:2])
self.ui.labresult.setText(result)
except:
self.ui.labresult.setText(u"没有查到相关记录")
示例4: Tray
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
class Tray():
def __init__(self, parent):
icon = AppIcon.getAppIcon()
if icon:
self.tray = QSystemTrayIcon(icon)
else:
self.tray = QSystemTrayIcon()
self.parent = parent
self.tray.setToolTip("Droid Navi")
# Menu
self.menu = QMenu()
self.menu.addAction("Show Connected List", partial(self.maximize))
self.menu.addAction("Options", partial(self.parent.openSettings))
self.menu.addAction("Exit", partial(self.parent.close))
self.tray.setContextMenu(self.menu)
# Connect handlers
self.tray.activated.connect(self.activated)
def getTray(self):
return self.tray
def display(self, show):
''' Toggle showing the tray '''
if show:
self.tray.show()
else:
self.tray.hide()
@pyqtSlot()
def maximize(self):
''' Show the main window and hide tray icon '''
self.display(False)
self.parent.maximizeFromTray()
@pyqtSlot()
def activated(self, reason):
if reason == QSystemTrayIcon.DoubleClick:
self.maximize()
示例5: Example
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.path=sys.path[0]
f=open('%s/ACCESS_KEY'% self.path,'r')
f1=open('%s/ACCESS_SECRET'% self.path,'r')
f2=open('%s/user_info'% self.path)
self.user_name=f2.readline().strip('\n')
self.user_id=f2.readline().strip('\n')
self.a=f.readline().strip('\n')
self.b=f1.readline().strip('\n')
f.close()
f1.close()
f2.close()
self.initUI()
def initUI(self):
self.icon=QSystemTrayIcon()
self.icon.isSystemTrayAvailable()
self.icon.setIcon( QtGui.QIcon('%s/web.png'% self.path) )
self.icon.setToolTip ( 'dubbleclick to maximize')
self.icon.show()
self.icon.activated.connect(self.activate)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.setGeometry(300, 300, 1500, 1000)
frame = QtGui.QFrame(parent=self)
frame.setStyleSheet("QFrame {background: rgba(0,0,0,50%)}")
box=QtGui.QHBoxLayout()
self.edit = QtGui.QLineEdit()
self.edit.setStyleSheet("background: rgba(0,0,0,100%); "" font-weight : bold;" "color: rgb(250,250,250);""border:5px solid ")
示例6: TrayController
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
class TrayController():
"""Display and control context menu."""
setings_win = None
def __init__(self):
"""Create TrayController."""
self._tray_ico = QSystemTrayIcon()
def set_menu(self, quit_callable, app_icon):
"""Show tray icon and sets its context menu items.
:param quit_callable: function to call when user choose Exit menu item
:type quit_callable: function
:param app_icon: QIcon object - tray icon image
:type app_icon: QIcon
"""
tray_menu = QMenu()
self._delay_menu = tray_menu.addAction(
QIcon(
os.path.join(PROGRAMM_RESOURCE_PATH, 'k-timer-icon.png')
),
QtCore.QCoreApplication.translate('TrayController', 'Delay')
)
delay_sub_menu = QMenu()
delay_sub_menu.addAction(
QtCore.QCoreApplication.translate('TrayController', '15 minutes'),
self.action_delay15
)
delay_sub_menu.addAction(
QtCore.QCoreApplication.translate('TrayController', '30 minutes'),
self.action_delay30
)
delay_sub_menu.addAction(
QtCore.QCoreApplication.translate('TrayController', '1 hour'),
self.action_delay60
)
delay_sub_menu.addAction(
QtCore.QCoreApplication.translate('TrayController', '2 hours'),
self.action_delay120
)
self._delay_menu.setMenu(delay_sub_menu)
self._resume_menu = tray_menu.addAction(
QIcon(
os.path.join(PROGRAMM_RESOURCE_PATH,
'App-Quick-restart-icon.png')
),
QtCore.QCoreApplication.translate('TrayController', 'Resume'),
self.action_resume
)
self._resume_menu.setVisible(False)
tray_menu.addAction(
QIcon(
os.path.join(PROGRAMM_RESOURCE_PATH, 'Settings-icon.png')
),
QtCore.QCoreApplication.translate('TrayController', 'Settings'),
self.show_settings
)
tray_menu.addSeparator()
tray_menu.addAction(
QIcon(
os.path.join(PROGRAMM_RESOURCE_PATH, 'delete-icon.png')
),
QtCore.QCoreApplication.translate('TrayController', 'Exit'),
quit_callable
)
self._tray_ico.setContextMenu(tray_menu)
self._tray_ico.setToolTip(PROGRAM_NAME)
self._tray_ico.setIcon(app_icon)
self._tray_ico.show()
self.setings_win = SettingsManager(self, app_icon)
def show_message(self, message):
"""Show message near tray icon.
(alternative to show message is via module
from PyQt4.QtGui import QMessageBox)
:param message: message string
:type message: str
"""
self._tray_ico.showMessage(
PROGRAM_NAME, message,
msecs=5000
)
# Functions - menu click actions
def toggle_delay_menu(self):
"""Toggle some context menu items.
(depending program delay is on or off)
"""
delay_on = self.setings_win.main_timer.delay_on
self._resume_menu.setVisible(delay_on)
self._delay_menu.setVisible(not delay_on)
self.setings_win.ui.notActiveLb.setText(
#.........这里部分代码省略.........
示例7: PigeonFeather
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
#.........这里部分代码省略.........
text = weather['text']
city = weather['city']
region = weather['region']
country = weather['country']
sunrise = weather['sunrise']
sunset = weather['sunset']
if self.config.get('units', 'wind') == 'mph':
windSpeed = weather['windSpeedMph']
speedUnit = 'mph'
else:
windSpeed = weather['windSpeedKph']
speedUnit = 'kph'
if self.config.get('units', 'pressure') == 'mb':
pressure = weather['pressureMb']
pressureUnit = 'mb'
else:
pressure = weather['pressureIn']
pressureUnit = 'in'
directionTextual = weather['directionTextual']
pressureTendancy = weather['pressureTendancy']
humidity = weather['humidity']
if self.config.get('units', 'distance') == 'mi':
visibility = weather['visibilityMi']
distanceUnit = 'mi'
else:
visibility = weather['visibilityKm']
distanceUnit = 'km'
# Get the filename for the icon to disply from the icon list map
# Generate the system tray icon and set it
iconFileName = self.codeToIconList[int(code)][1]
icon = self.createWeatherIcon('images/22/' + iconFileName, str(temp))
self.setTrayIcon(icon)
# Set the tool tip
tempString = str(temp) + '°' + tempUnit + ' ' + text
self.trayIcon.setToolTip(tempString)
# Update the weather report dialog
self.weatherDialog.labelLastUpdate.setText( \
fetched.strftime('%H:%M:%S'))
self.weatherDialog.setWindowTitle('Weather report for ' + city + \
', ' + region + ' ' + country)
self.weatherDialog.labelTemp.setText(tempString)
self.weatherDialog.labelSunrise.setText(sunrise)
self.weatherDialog.labelSunset.setText(sunset)
self.weatherDialog.labelWindChill.setText(str(chill) + \
'°' + tempUnit)
self.weatherDialog.labelWindSpeed.setText(str(windSpeed) + ' ' + \
speedUnit)
self.weatherDialog.labelWindDirection.setText(directionTextual)
self.weatherDialog.labelHumidity.setText(str(humidity) + '%')
self.weatherDialog.labelVisibility.setText(str(visibility) + ' ' + \
distanceUnit)
self.weatherDialog.labelPressure.setText(str(pressure) + ' ' + \
pressureUnit)
self.weatherDialog.labelRising.setText(pressureTendancy)
# Set the image
self.weatherDialog.labelIcon.setPixmap(QPixmap('images/64/' + \
iconFileName))
# TODO - this should really be in another class
def createWeatherIcon(self, iconFileName, temp):
"""Create the icon to display in the tray"""
# Create a map of what image to use based on code
# Start by creating a transparent image to paint on
print(('Using' + iconFileName))
icon = QPixmap(22, 22)
icon.fill(Qt.transparent)
# Create a painter to paint on to the icon and draw on the text
painter = QPainter(icon)
painter.setOpacity(0.5)
# Draw text of temperature
font = QFont('Times', 10, QFont.Black)
painter.setFont(font)
painter.setPen(QColor('red'))
painter.drawPixmap(QPoint(0, 0), QPixmap(iconFileName))
painter.setOpacity(1)
painter.drawText(5, 15, temp)
painter.end()
# Return the icon
return QIcon(icon)
def setTrayIcon(self, icon):
"""Set the tray icon"""
self.trayIcon.setIcon(icon)
self.trayIcon.show()
def quitApp(self):
"""Exit the application"""
sys.exit(0)
示例8: __init__
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
#.........这里部分代码省略.........
self.last_message = None
self.timer = QTimer()
QObject.connect( self.timer, SIGNAL('timeout()'), self.update_info )
self.ppid = os.getppid()
def prepare_exit( self ):
self.timer.stop()
if not self.status_icon is None:
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.prepare_exit()
def update_info( self ):
if not tools.is_process_alive( self.ppid ):
self.prepare_exit()
self.qapp.exit(0)
return
message = self.snapshots.get_take_snapshot_message()
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.wrap_line(message[1],\
size = 80,\
delimiters = '',\
new_line_indicator = '') \
))
self.status_icon.setToolTip(message[1])
pg = progress.ProgressFile(self.config)
if pg.isFileReadable():
pg.load()
percent = pg.get_int_value('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.get_str_value(key, '')
if not value:
continue
yield txt + ' ' + value
def onStartBIT(self):
profileID = self.config.get_current_profile()
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.cb_decode.setChecked(self.btnDecode.isChecked())
dlg.exec_()
def onBtnDecode(self, checked):
if checked:
self.decode = encfstools.Decode(self.config)
self.last_message = None
self.update_info()
else:
self.decode = None
示例9: __init__
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
def __init__(self, parent=None):
" Initialize QWidget inside MyMainWindow "
super(MyMainWindow, self).__init__(parent)
QWidget.__init__(self)
self.statusBar().showMessage(" {}".format(__doc__))
self.setStyleSheet("QStatusBar{color:grey;}")
self.setWindowTitle(__doc__)
self.setWindowIcon(QIcon.fromTheme("face-monkey"))
self.setFont(QFont("Ubuntu Light", 10))
self.setMaximumSize(QDesktopWidget().screenGeometry().width(), QDesktopWidget().screenGeometry().height())
# directory auto completer
self.completer = QCompleter(self)
self.dirs = QDirModel(self)
self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
self.completer.setModel(self.dirs)
self.completer.setCaseSensitivity(Qt.CaseInsensitive)
self.completer.setCompletionMode(QCompleter.PopupCompletion)
# Proxy support, by reading http_proxy os env variable
proxy_url = QUrl(environ.get("http_proxy", ""))
QNetworkProxy.setApplicationProxy(
QNetworkProxy(
QNetworkProxy.HttpProxy if str(proxy_url.scheme()).startswith("http") else QNetworkProxy.Socks5Proxy,
proxy_url.host(),
proxy_url.port(),
proxy_url.userName(),
proxy_url.password(),
)
) if "http_proxy" in environ else None
print((" INFO: Proxy Auto-Config as " + str(proxy_url)))
# basic widgets layouts and set up
self.mainwidget = QTabWidget()
self.mainwidget.setToolTip(__doc__)
self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu)
self.mainwidget.tabCloseRequested.connect(lambda: self.mainwidget.setTabPosition(randint(0, 3)))
# if self.mainwidget.tabPosition() == 0
# else self.mainwidget.setTabPosition(0))
self.mainwidget.setStyleSheet("QTabBar{color:white;font-weight:bold;}")
self.mainwidget.setTabBar(TabBar(self))
self.mainwidget.setMovable(True)
self.mainwidget.setTabsClosable(True)
self.mainwidget.setTabShape(QTabWidget.Triangular)
self.setCentralWidget(self.mainwidget)
self.dock1 = QDockWidget()
self.dock2 = QDockWidget()
self.dock3 = QDockWidget()
for a in (self.dock1, self.dock2, self.dock3):
a.setWindowModality(Qt.NonModal)
a.setWindowOpacity(0.9)
a.setWindowTitle(__doc__ if a.windowTitle() == "" else a.windowTitle())
a.setStyleSheet(" QDockWidget::title{text-align:center;}")
self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"), "Double Click Me")
# Paleta de colores para pintar transparente
self.palette().setBrush(QPalette.Base, Qt.transparent)
self.setPalette(self.palette())
self.setAttribute(Qt.WA_OpaquePaintEvent, False)
# toolbar and basic actions
self.toolbar = QToolBar(self)
self.toolbar.setIconSize(QSize(24, 24))
# spacer widget for left
self.left_spacer = QWidget(self)
self.left_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
# spacer widget for right
self.right_spacer = QWidget(self)
self.right_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
qaqq = QAction(QIcon.fromTheme("application-exit"), "Quit", self)
qaqq.setShortcut("Ctrl+Q")
qaqq.triggered.connect(exit)
qamin = QAction(QIcon.fromTheme("go-down"), "Minimize", self)
qamin.triggered.connect(lambda: self.showMinimized())
qamax = QAction(QIcon.fromTheme("go-up"), "Maximize", self)
qanor = QAction(QIcon.fromTheme("view-fullscreen"), "AutoCenter AutoResize", self)
qanor.triggered.connect(self.center)
qatim = QAction(QIcon.fromTheme("mail-signed-verified"), "View Date and Time", self)
qatim.triggered.connect(self.timedate)
qabug = QAction(QIcon.fromTheme("help-about"), "Report a Problem", self)
qabug.triggered.connect(
lambda: qabug.setDisabled(True)
if not call("xdg-open mailto:" + "[email protected]".decode("rot13"), shell=True)
else " ERROR "
)
qamax.triggered.connect(lambda: self.showMaximized())
qaqt = QAction(QIcon.fromTheme("help-about"), "About Qt", self)
qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self))
qakde = QAction(QIcon.fromTheme("help-about"), "About KDE", self)
if KDE:
qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE)
qaslf = QAction(QIcon.fromTheme("help-about"), "About Self", self)
if KDE:
qaslf.triggered.connect(KAboutApplicationDialog(aboutData, self).exec_)
else:
qaslf.triggered.connect(
lambda: QMessageBox.about(
self.mainwidget,
__doc__,
"".join(
#.........这里部分代码省略.........
示例10: GlobalSysTray
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
class GlobalSysTray(object):
def __init__(self, parent, name, icon):
object.__init__(self)
self._app = None
self._parent = parent
self._gtk_running = False
self._quit_added = False
self.act_indexes = []
self.sep_indexes = []
self.menu_indexes = []
if TrayEngine == "KDE":
self.menu = KMenu(parent)
self.menu.setTitle(name)
self.tray = KStatusNotifierItem()
self.tray.setAssociatedWidget(parent)
self.tray.setCategory(KStatusNotifierItem.ApplicationStatus)
self.tray.setContextMenu(self.menu)
self.tray.setIconByPixmap(getIcon(icon))
self.tray.setTitle(name)
self.tray.setToolTipTitle(" ")
self.tray.setToolTipIconByPixmap(getIcon(icon))
# Double-click is managed by KDE
elif TrayEngine == "AppIndicator":
self.menu = Gtk.Menu()
self.tray = AppIndicator.Indicator.new(name, icon, AppIndicator.IndicatorCategory.APPLICATION_STATUS)
self.tray.set_menu(self.menu)
# Double-click is not possible with App-Indicators
elif TrayEngine == "Qt":
self.menu = QMenu(parent)
self.tray = QSystemTrayIcon(getIcon(icon))
self.tray.setContextMenu(self.menu)
self.tray.setParent(parent)
self.tray.connect(self.tray, SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.qt_systray_clicked)
# -------------------------------------------------------------------------------------------
def addAction(self, act_name_id, act_name_string, is_check=False):
if TrayEngine == "KDE":
act_widget = KAction(act_name_string, self.menu)
act_widget.setCheckable(is_check)
self.menu.addAction(act_widget)
elif TrayEngine == "AppIndicator":
if is_check:
act_widget = Gtk.CheckMenuItem(act_name_string)
else:
act_widget = Gtk.ImageMenuItem(act_name_string)
act_widget.set_image(None)
act_widget.show()
self.menu.append(act_widget)
elif TrayEngine == "Qt":
act_widget = QAction(act_name_string, self.menu)
act_widget.setCheckable(is_check)
self.menu.addAction(act_widget)
else:
act_widget = None
act_obj = [None, None, None, None]
act_obj[iActNameId] = act_name_id
act_obj[iActWidget] = act_widget
self.act_indexes.append(act_obj)
def addSeparator(self, sep_name_id):
if TrayEngine == "KDE":
sep_widget = self.menu.addSeparator()
elif TrayEngine == "AppIndicator":
sep_widget = Gtk.SeparatorMenuItem()
sep_widget.show()
self.menu.append(sep_widget)
elif TrayEngine == "Qt":
sep_widget = self.menu.addSeparator()
else:
sep_widget = None
sep_obj = [None, None, None]
sep_obj[iSepNameId] = sep_name_id
sep_obj[iSepWidget] = sep_widget
self.sep_indexes.append(sep_obj)
def addMenu(self, menu_name_id, menu_name_string):
if TrayEngine == "KDE":
menu_widget = KMenu(menu_name_string, self.menu)
self.menu.addMenu(menu_widget)
elif TrayEngine == "AppIndicator":
menu_widget = Gtk.MenuItem(menu_name_string)
menu_parent = Gtk.Menu()
menu_widget.set_submenu(menu_parent)
#.........这里部分代码省略.........
示例11: __init__
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
def __init__(self, AUTO):
' Initialize QWidget inside MyMainWindow '
super(MyMainWindow, self).__init__()
QWidget.__init__(self)
self.auto = AUTO
self.statusBar().showMessage(' {}'.format(__doc__))
self.setStyleSheet('QStatusBar{color:grey;}')
self.setWindowTitle(__doc__)
self.setWindowIcon(QIcon.fromTheme("face-monkey"))
self.setFont(QFont('Ubuntu Light', 10))
self.setMaximumSize(QDesktopWidget().screenGeometry().width(),
QDesktopWidget().screenGeometry().height())
self.base = path.abspath(path.join(getcwd(), str(datetime.now().year)))
# directory auto completer
self.completer = QCompleter(self)
self.dirs = QDirModel(self)
self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
self.completer.setModel(self.dirs)
self.completer.setCaseSensitivity(Qt.CaseInsensitive)
self.completer.setCompletionMode(QCompleter.PopupCompletion)
# process
self.process1 = None
self.process2 = None
self.cmd1 = 'nice -n {n} arecord{v} -f {f} -c {c} -r {b} -t raw'
self.cmd2 = 'oggenc - -r -C {c} -R {b} -q {q} {d}{t}{a} -o {o}'
self.process3 = QProcess(self)
#self.process3.finished.connect(self.on_process3_finished)
#self.process3.error.connect(self.on_process3_error)
self.cmd3 = ('nice -n 20 ' +
'sox "{o}" -n spectrogram -x {x} -y {y} -z 99 -t "{o}" -o "{o}.png"')
self.actual_file = ''
# re starting timers, one stops, one starts
self.timerFirst = QTimer(self)
self.timerFirst.timeout.connect(self.end)
self.timerSecond = QTimer(self)
self.timerSecond.timeout.connect(self.run)
# Proxy support, by reading http_proxy os env variable
proxy_url = QUrl(environ.get('http_proxy', ''))
QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy
if str(proxy_url.scheme()).startswith('http')
else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(),
proxy_url.userName(), proxy_url.password())) \
if 'http_proxy' in environ else None
print((' INFO: Proxy Auto-Config as ' + str(proxy_url)))
# basic widgets layouts and set up
self.mainwidget = QTabWidget()
self.mainwidget.setToolTip(__doc__)
self.mainwidget.setMovable(True)
self.mainwidget.setTabShape(QTabWidget.Triangular)
self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu)
self.mainwidget.setStyleSheet('QTabBar{color:white;font-weight:bold;}')
self.mainwidget.setTabBar(TabBar(self))
self.mainwidget.setTabsClosable(False)
self.setCentralWidget(self.mainwidget)
self.dock1 = QDockWidget()
self.dock2 = QDockWidget()
self.dock3 = QDockWidget()
self.dock4 = QDockWidget()
self.dock5 = QDockWidget()
for a in (self.dock1, self.dock2, self.dock3, self.dock4, self.dock5):
a.setWindowModality(Qt.NonModal)
# a.setWindowOpacity(0.9)
a.setWindowTitle(__doc__
if a.windowTitle() == '' else a.windowTitle())
a.setStyleSheet('QDockWidget::title{text-align:center;}')
self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"),
'Double Click Me')
# Paleta de colores para pintar transparente
self.palette().setBrush(QPalette.Base, Qt.transparent)
self.setPalette(self.palette())
self.setAttribute(Qt.WA_OpaquePaintEvent, False)
# toolbar and basic actions
self.toolbar = QToolBar(self)
self.toolbar.setIconSize(QSize(24, 24))
# spacer widget for left
self.left_spacer = QWidget(self)
self.left_spacer.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding)
# spacer widget for right
self.right_spacer = QWidget(self)
self.right_spacer.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding)
qaqq = QAction(QIcon.fromTheme("application-exit"), 'Quit', self)
qaqq.setShortcut('Ctrl+Q')
qaqq.triggered.connect(exit)
qamin = QAction(QIcon.fromTheme("go-down"), 'Minimize', self)
qamin.triggered.connect(lambda: self.showMinimized())
qamax = QAction(QIcon.fromTheme("go-up"), 'Maximize', self)
qanor = QAction(QIcon.fromTheme("view-fullscreen"),
'AutoCenter AutoResize', self)
qanor.triggered.connect(self.center)
#.........这里部分代码省略.........
示例12: MainWindow
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.settings = QSettings(QSettings.IniFormat, QSettings.UserScope, VENDOR, APP)
self.setup = ConfigDialog(None, Qt.WindowSystemMenuHint | Qt.WindowTitleHint)
self.setup.setModal(True)
centerOnScreen(self.setup)
self.setup.wake.connect(self.wake)
self.setup.serversChanged.connect(self.updateMenu)
self.menuServers = []
self.trayIcon = QSystemTrayIcon(QIcon("res/power.png"), self)
self.trayIcon.activated.connect(self.activated)
menu = QMenu()
self.populateMenuFromSettings(menu)
menu.addSeparator()
self.setupAction = menu.addAction(QIcon('res/setup.png'), "Configure")
self.setupAction.triggered.connect(self.setup.show)
menu.addSeparator()
exitAction = menu.addAction("Exit")
exitAction.triggered.connect(self.close)
self.trayIcon.setContextMenu(menu)
self.trayIcon.setToolTip("Wake on LAN")
self.trayIcon.show()
servers = self.settings.beginReadArray("servers")
self.settings.endArray()
if not servers:
self.setup.show()
def populateMenuFromSettings(self, menu):
"""
:type menu: QMenu
"""
actions = menu.actions()
before = actions[0] if actions else None
title = QWidgetAction(menu)
label = QLabel("Hosts")
font = label.font()
px = font.pointSize()
font.setBold(True)
font.setPointSize(px * 1.5)
label.setFont(font)
label.setMargin(4)
label.setIndent(10)
# label.setStyleSheet("font-weight: bold; margin: 4px 2px; border-bottom: 2px solid black")
title.setDefaultWidget(label)
menu.insertAction(before, title)
self.menuServers.append(title)
servers = self.settings.beginReadArray("servers")
for d in range(servers):
self.settings.setArrayIndex(d)
server = Server.fromSettings(self.settings)
action = QAction(QIcon("res/server.png"), server.alias, menu)
menu.insertAction(before, action)
action.setData(server)
action.triggered.connect(self.wakeFromMenu)
self.menuServers.append(action)
self.settings.endArray()
def activated(self, reason):
if reason == QSystemTrayIcon.DoubleClick:
self.setup()
elif reason == QSystemTrayIcon.Trigger:
menu = QMenu()
self.populateMenuFromSettings(menu)
menu.exec_(QCursor.pos())
def updateMenu(self):
menu = self.trayIcon.contextMenu()
for action in self.menuServers:
action.setData(None)
menu.removeAction(action)
self.populateMenuFromSettings(menu)
def wakeFromMenu(self):
action = self.sender()
server = action.data().toPyObject()
self.wake(server)
def wake(self, server):
if QMessageBox.Yes == QMessageBox.question(self, "Wake on LAN", "Wake %s?" % server.alias, QMessageBox.Yes|QMessageBox.No):
magic = '\xFF' * 6
#.........这里部分代码省略.........
示例13: GuiApplicationLinux
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
class GuiApplicationLinux(GuiApplicationBase):
def __init__(self, executable, iconPath, parent=None):
super(GuiApplicationLinux, self).__init__(iconPath)
self.eventLoop = "qt"
self.app = QApplication(sys.argv) # this should be done before anything else
self.executable = executable
if QIcon.hasThemeIcon(iconPath):
icon = QIcon.fromTheme(iconPath)
else:
icon = QIcon(iconPath)
self.statusIcon = QSystemTrayIcon(icon, parent)
self.menu = QMenu(parent)
exitAction = self.menu.addAction("Exit")
exitAction.triggered.connect(self.quit)
self.statusIcon.setContextMenu(self.menu)
def activate(reason):
if reason == QSystemTrayIcon.Trigger:
return self.launchExecutable()
QObject.connect(self.statusIcon, SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), activate)
self.statusIcon.show()
# A portable icon wrapper. Notify2 demands icon class to be compatible with GdkPixbuf so we
# provide a compatibility layer
class IconWrapper(object):
def __init__(self, iconName):
if QIcon.hasThemeIcon(iconName):
icon = QIcon.fromTheme(iconName)
else:
icon = QIcon(iconName)
size = icon.availableSizes()[0]
self.image = icon.pixmap(size).toImage().convertToFormat(QImage.Format_ARGB32)
self.image = self.image.rgbSwapped() # otherwise colors are weird :/
def get_width(self):
return self.image.width()
def get_height(self):
return self.image.height()
def get_rowstride(self):
return self.image.bytesPerLine()
def get_has_alpha(self):
return self.image.hasAlphaChannel()
def get_bits_per_sample(self):
return self.image.depth() // self.get_n_channels()
def get_n_channels(self):
if self.image.isGrayscale():
return 1
elif self.image.hasAlphaChannel():
return 4
else:
return 3
def get_pixels(self):
return self.image.bits().asstring(self.image.numBytes())
# end of wrapper class
def getNotificationIcon(self):
try:
return self.IconWrapper(self.iconPath)
except:
logging.error("Failed to get notification icon")
return None
def refreshToolTip(self, players):
self.statusIcon.setToolTip(self.formTooltip(players))
def launchExecutable(self, *args):
try:
subprocess.Popen(self.executable, shell=True)
except:
logging.error("Unable to run {0}".format(self.cmd))
def run(self):
sys.exit(self.app.exec_())
def quit(self):
self.timer.cancel()
sys.exit(0)
示例14: Example
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.path=sys.path[0]
f=open('%s/ACCESS_KEY'% self.path,'r')
f1=open('%s/ACCESS_SECRET'% self.path,'r')
f2=open('%s/user_info'% self.path)
self.user_name=f2.readline().strip('\n')
self.user_id=f2.readline().strip('\n')
self.a=f.readline().strip('\n')
self.b=f1.readline().strip('\n')
f.close()
f1.close()
f2.close()
self.initUI()
def initUI(self):
self.icon=QSystemTrayIcon()
self.icon.isSystemTrayAvailable()
self.icon.setIcon( QtGui.QIcon('%s/web.png'% self.path) )
self.icon.setToolTip ( 'dubbleclick to maximize')
self.icon.show()
self.icon.activated.connect(self.activate)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.setGeometry(300, 300, 1500, 1000)
frame = QtGui.QFrame(parent=self)
frame.setStyleSheet("QFrame {background: rgba(0,0,0,50%)}")
box=QtGui.QHBoxLayout()
self.edit = QtGui.QLineEdit()
self.edit.setStyleSheet("background: rgba(0,0,0,100%); "" font-weight : bold;" "color: rgb(250,250,250);""border:5px solid ")
self.edit.setToolTip('please <b>Enter your tweet here </b> ')
self.edit.returnPressed.connect(self.returnPressed)
box.addWidget(self.edit)
frame.setLayout(box)
qbtn1 = QtGui.QPushButton('quit', self)
qbtn1.clicked.connect(self.close)
qbtn1.setStyleSheet( "background: rgba(0,0,0,100%); "" font-weight : bold;" "color: rgb(250,250,250);""border:5px solid ")
box.addWidget(qbtn1)
self.statusBar().setStyleSheet("background: rgba(0,0,0,100%);"" font-weight : bold;" "color: rgb(250,250,250)")
self.statusBar().showMessage('Press Enter to send Tweet and press ESC to minimize to tray ')
self.setCentralWidget(frame)
self.setWindowIcon(QtGui.QIcon('%s/web.png' % self. path))
self.setWindowTitle('Tweet Fast ')
self.center()
self.show()
self.twitter_auth()
def twitter_auth(self):
CONSUMER_KEY = 'VQLDtkDTlbAmT95m5cMsYQ'
CONSUMER_SECRET = 'bAC0BF69qiEVARJlfFJZZCDQ9mrcqofq16ilQ4OjU'
ACCESS_KEY=self.a
ACCESS_SECRET=self.b
self.auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
self.auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Escape:
print 'Escape wass pressed '
self.icon.show()
self.hide()
def activate(self,reason ):
print reason
if reason==2:
self.show()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def returnPressed(self):
path=sys.path[0]
tweet = self.edit.text()
api = tweepy.API(self.auth)
self.statusBar().showMessage('Sending... ')
api.update_status(tweet)
self.statusBar().showMessage('Your Tweet was send ')
n = pynotify.Notification(" @ %s "% self.user_name , "your tweet was send ","%s/%s.jpg" % (path,self.user_id))
n.set_hint('x', 200)
n.set_hint('y', 400)
pynotify.init('n')
#.........这里部分代码省略.........
示例15: Example
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setToolTip [as 别名]
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.path = sys.path[0]
f = open("%s/ACCESS_KEY" % self.path, "r")
f1 = open("%s/ACCESS_SECRET" % self.path, "r")
f2 = open("%s/user_info" % self.path)
self.user_name = f2.readline().strip("\n")
self.user_id = f2.readline().strip("\n")
self.a = f.readline().strip("\n")
self.b = f1.readline().strip("\n")
f.close()
f1.close()
f2.close()
self.initUI()
def initUI(self):
self.icon = QSystemTrayIcon()
self.icon.isSystemTrayAvailable()
self.icon.setIcon(QtGui.QIcon("%s/me.jpg" % self.path))
self.icon.setToolTip("dubbleclick untuk maximize")
self.icon.show()
self.icon.activated.connect(self.activate)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.setGeometry(150, 150, 500, 200)
frame = QtGui.QFrame(parent=self)
frame.setStyleSheet("QFrame {background: rgba(0,0,0,50%)}")
box = QtGui.QHBoxLayout()
self.edit = QtGui.QLineEdit()
self.edit.setStyleSheet(
"background: rgba(0,0,0,100%); " " font-weight : bold;" "color: rgb(250,250,250);" "border:5px solid "
)
self.edit.setToolTip("Tolong <b>Massukan tweet Anda di sini </b> ")
self.edit.returnPressed.connect(self.returnPressed)
box.addWidget(self.edit)
frame.setLayout(box)
qbtn1 = QtGui.QPushButton("keluar", self)
qbtn1.clicked.connect(self.close)
qbtn1.setStyleSheet(
"background: rgba(0,0,0,100%); " " font-weight : bold;" "color: rgb(250,250,250);" "border:5px solid "
)
box.addWidget(qbtn1)
self.statusBar().setStyleSheet(
"background: rgba(0,0,0,100%);" " font-weight : bold;" "color: rgb(250,250,250)"
)
self.statusBar().showMessage("Tekan enter untuk mengirim twitter, ESC untuk minimize")
self.setCentralWidget(frame)
self.setWindowIcon(QtGui.QIcon("%s/me.jpg" % self.path))
self.setWindowTitle("Twitter Client With PyQt4")
self.center()
self.show()
self.twitter_auth()
def twitter_auth(self):
CONSUMER_KEY = "gYMpKX6YWDP5rBwvCcriQ"
CONSUMER_SECRET = "ulK4WA6gtB5FekyPYRrOXVCxeqvwP66leFfNq5DY"
ACCESS_KEY = self.a
ACCESS_SECRET = self.b
self.auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
self.auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Escape:
print "Escape wass pressed "
self.icon.show()
self.hide()
def activate(self, reason):
print reason
if reason == 2:
self.show()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def returnPressed(self):
path = sys.path[0]
tweet = self.edit.text()
api = tweepy.API(self.auth)
self.statusBar().showMessage("Mengirim . .. ")
api.update_status(tweet)
self.statusBar().showMessage("Twitter Anda terkirim ! ")
n = pynotify.Notification(
" @ %s " % self.user_name, "twitter Anda terkirim ", "%s/%s.jpg" % (path, self.user_id)
)
n.set_hint("x", 200)
#.........这里部分代码省略.........