本文整理汇总了Python中PyQt4.QtGui.QSystemTrayIcon.setIcon方法的典型用法代码示例。如果您正苦于以下问题:Python QSystemTrayIcon.setIcon方法的具体用法?Python QSystemTrayIcon.setIcon怎么用?Python QSystemTrayIcon.setIcon使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtGui.QSystemTrayIcon
的用法示例。
在下文中一共展示了QSystemTrayIcon.setIcon方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Tray
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [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: SystemTrayRemoto
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [as 别名]
class SystemTrayRemoto(ServicoFuncao):
def __init__(self, parent=None):
super().__init__(5433, 5433, parent)
self.systemTray = QSystemTrayIcon()
self.systemTray.setIcon(QIcon("bad.svg"))
self.systemTray.show()
@send_funcao
def ativar(self, titulo, mensagem):
self.systemTray.showMessage(titulo, mensagem, QSystemTrayIcon.Information, 3000)
示例3: StartQT4
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [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: sysBaloon
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [as 别名]
class sysBaloon(QMainWindow):
def baloon(self, t, m, tm=50000):
self.trayicon = QSystemTrayIcon(self)
if self.trayicon.supportsMessages():
icona = QIcon('py.ico')
self.trayicon.setIcon(icona)
self.trayicon.show()
self.trayicon.showMessage(t, m, msecs=tm)
time.sleep(10)
self.trayicon.hide()
else:
print "This Function isn't supported."
choose = raw_input("Would you enable it? Y/N \n --> ")
if choose == "Y":
shell = os.popen('enable_baloon.reg')
print "Run again this program"
elif choose == "N":
print "You don't use this program without baloon enabled."
else:
print "You have insert wrong char."
示例5: Example
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [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: __init__
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [as 别名]
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
uic.loadUi("./MainWindow/form.ui", self)
self.setWindowTitle("NFS-List")
self.setLayout(self.gridLayout)
self.setGeometry(100, 100, 640, 480)
self.listWidget.setViewMode(QtGui.QListView.IconMode)
self.listWidget.setMovement(QtGui.QListWidget.Static)
self.ipv6_enable = True # False
self.addr_ipv4 = None
self.addr_ipv6 = None
self.addr_ipv4_array = []
self.addr_ipv6_array = []
self.time = 1
self.hosts = []
self.icon = QtGui.QIcon("./MainWindow/NAS-icon.png")
self.setWindowIcon(self.icon)
#Tray
tray_menu = QtGui.QMenu(self)
show_hide_action = QAction("Show/Hide", self)
quitAction = QAction("Quit", self)
tray_menu.addAction(show_hide_action)
tray_menu.addAction(quitAction)
tray = QSystemTrayIcon(self)
tray.setIcon(self.icon)
tray.setContextMenu(tray_menu)
tray.setToolTip(self.windowTitle())
tray.show()
#
show_hide_action.triggered.connect(self.showHideWindow)
quitAction.triggered.connect(QtGui.qApp.quit)
#end tray
# self.ico.addPixmap(self.pixmap)
ifaces = QtNetwork.QNetworkInterface.allInterfaces()
for iface in ifaces:
for addr_iface in iface.addressEntries():
if addr_iface.ip() != QtNetwork.QHostAddress(QtNetwork.QHostAddress.LocalHost) and \
addr_iface.ip() != QtNetwork.QHostAddress(QtNetwork.QHostAddress.LocalHostIPv6):
if addr_iface.ip().toIPv4Address():
self.addr_ipv4_array.append(addr_iface)
if self.ipv6_enable:
if addr_iface.ip().toIPv6Address():
self.addr_ipv6_array.append(addr_iface)
if len(self.addr_ipv4_array) >= 1:
self.addr_ipv4 = self.addr_ipv4_array[0].ip().toString()
#ip data#
addr_mask = self.addr_ipv4_array[0].netmask().toString()
#addr_mask = '255.255.255.192'
__list_aprefix = addr_mask.split('.')
cidr_ipv4 = 0
bn = '0b'
baddr = '0b'
for i in __list_aprefix:
cidr_ipv4 += rpclib.bit_count(int(i))
bn += bin(int(i))[2:]
print("cidr:", cidr_ipv4)
print(bn)
#
total_ip_count = (2 ** (32 - cidr_ipv4)) - 2
print('total_ip_count:', total_ip_count)
print(self.addr_ipv4)
int_net_ipv4 = rpclib.ip2int(self.addr_ipv4) & rpclib.ip2int(addr_mask)
net_ipv4 = rpclib.int2ip(int_net_ipv4)
#abc = ClockThread(self.time, self.add_new_item)
#abc.start()
#self.add_new_item('t34', 't32')
self.scan_network = ThreadScanNetwork(10, net_ipv4, cidr_ipv4, self, 1.2)
self.scan_network.start()
self.check_host = ThreadCheckHost(self.hosts, self)
self.check_host.start()
#self.add_host({"host":"100.64.0.1","structures":[{'groups': [b'*'], 'dir': b'/srv/NFS'}]})
"""
self.listWidget.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
self.actionInfo = QAction("Info", self.listWidget)
self.actionMount = QAction("Mount", self.listWidget)
self.listWidget.addAction(self.actionMount)
self.listWidget.addAction(self.actionInfo)
self.actionInfo.triggered.connect(self.showInfo)
self.actionMount.triggered.connect(self.my_method)
"""
self.listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
#.........这里部分代码省略.........
示例7: QSystemTrayIcon
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [as 别名]
sys.exit(0)
except dbus.exceptions.DBusException:
QMessageBox.critical(None, "Can't connect",
"""Can't connect to pyUmlaut0r daemon.\nYou should first start a daemon by calling:\n'pyUmlaut0r.py -d'.""")
print "can't connect to daemon"
sys.exit(1)
#set process name
utils.setProcessName("pyUmlaut0r")
#create trayIcon
trayIcon = QSystemTrayIcon()
trayIcon.setIcon(QIcon(":/pyUmlaut0rIcon.png"))
trayIcon.setContextMenu(utils.createMenu())
trayIcon.show()
#dbus "daemon"
DBusQtMainLoop(set_as_default = True)
class DBusInterface(dbus.service.Object):
def __init__(self):
busName = dbus.service.BusName('org.documentroot.umlaut0r', \
bus = dbus.SessionBus())
dbus.service.Object.__init__(self, busName, '/umlaut0r')
@dbus.service.method('org.documentroot.umlaut0r', in_signature='s')
def toClipboard(self, s):
utils.toClipboard(s)
示例8: _fromUtf8
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [as 别名]
try:
_fromUtf8 = QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
app = QApplication(sys.argv)
app.setQuitOnLastWindowClosed(False)
m = QWidget()
d = QMainWindow(m)
t = QSystemTrayIcon(m)
t.setIcon(QIcon("icon/tray.png"))
ui = Ui_UniFileSyncPop()
ui.setupUi(d)
d.setFixedSize(d.size())
req = {"type": "request"}
confManager = ConfManager.getManager()
fts = confManager.getValue("common", "folders")
ui.nameLabel.setText(confManager.getValue("UI", "username"))
示例9: KerberusSystray
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [as 别名]
#.........这里部分代码省略.........
)
#accion habilitar filtrado
self.habilitarFiltradoAction = self.menu.addAction(
self.style.standardIcon(QStyle.SP_DialogYesButton),
'Habilitar Filtrado'
)
self.habilitarFiltradoAction.setVisible(False)
#cambiar password
self.cambiarPasswordAction = self.menu.addAction(
self.style.standardIcon(QStyle.SP_BrowserReload),
'Cambiar password de administrador'
)
#accion salir
self.exitAction = self.menu.addAction(
self.style.standardIcon(QStyle.SP_TitleBarCloseButton),
'Salir')
#SIGNAL->SLOT
QObject.connect(
self.exitAction,
SIGNAL("triggered()"),
lambda: sys.exit()
)
QObject.connect(
self.menu, SIGNAL("clicked()"),
lambda: self.menu.popup(QCursor.pos())
)
QObject.connect(
self.deshabilitarFiltradoAction,
SIGNAL("triggered()"),
self.deshabilitarFiltradoWindow
)
QObject.connect(
self.habilitarFiltradoAction,
SIGNAL("triggered()"),
self.habilitarFiltradoWindow
)
QObject.connect(
self.cambiarPasswordAction,
SIGNAL("triggered()"),
self.cambiarPasswordWindow
)
#SystemTray
#self.tray = QSystemTrayIcon(QIcon(pixmap), self)
self.tray = QSystemTrayIcon(self.style.standardIcon(QStyle.SP_DialogYesButton), self)
self.tray.setToolTip('Kerberus Control Parental - Activado')
self.tray.setContextMenu(self.menu)
self.tray.setVisible(True)
QObject.connect(
self.tray,
SIGNAL("messageClicked()"),
self.noMostrarMasMensaje
)
if self.mostrarMensaje:
self.tray.showMessage(
u'Kerberus Control Parental',
u'Filtro de Protección para menores de edad Activado',
2000
)
#def closeEvent(self, event):
#event.ignore()
#self.hide()
def noMostrarMasMensaje(self):
try:
open('dontShowMessage','a').close()
except IOError:
print 'No se pudo crear el archivo dontShowMessage'
def deshabilitarFiltradoWindow(self):
webbrowser.open(
'http://inicio.kerberus.com.ar/!DeshabilitarFiltrado!',
new=2
)
self.habilitarFiltradoAction.setVisible(True)
self.deshabilitarFiltradoAction.setVisible(False)
self.tray.setIcon(self.style.standardIcon(QStyle.SP_DialogNoButton))
self.tray.setToolTip('Kerberus Control Parental')
def habilitarFiltradoWindow(self):
webbrowser.open(
'http://inicio.kerberus.com.ar/!HabilitarFiltrado!',
new=2
)
self.habilitarFiltradoAction.setVisible(False)
self.deshabilitarFiltradoAction.setVisible(True)
self.tray.setIcon(self.style.standardIcon(QStyle.SP_DialogYesButton))
self.tray.setToolTip('Kerberus Control Parental - Activado')
def cambiarPasswordWindow(self):
webbrowser.open(
'http://inicio.kerberus.com.ar/!CambiarPassword!',
new=2
)
示例10: SingleApplication
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [as 别名]
class SingleApplication(QApplication):
def __init__(self, *args):
QApplication.__init__(self, *args)
self._memory = QSharedMemory(self)
self._memory.setKey("d2mp")
if self._memory.attach():
self._running = True
else:
self._running = False
if not self._memory.create(1):
raise RuntimeError(self._memory.errorString().toLocal8Bit().data())
def is_running(self):
return self._running
def exec_(self):
self._create_tray_icon()
self._create_mod_manager()
self._start_file_watcher()
self._create_socket()
Settings()
return super(SingleApplication, self).exec_()
def _create_mod_manager(self):
self.manager = ModManager()
self.manager.mod_game_info()
self.manager.signals.message.connect(self.show_message_from_mod_manager)
self.manager.signals.error.connect(self.show_error_from_mod_manager)
def _create_socket(self):
self.socket = ConnectionManager()
self.manager.signals.contact_server.connect(self.socket.send)
self.socket.message.connect(self.show_message_from_socket)
self.socket.error.connect(self.show_error_from_socket)
@property
def _watcher_file_name(self):
return "d2mp.pid"
def _start_file_watcher(self):
self.watcher = QFileSystemWatcher()
self.watcher_file_path = join(abspath("."), self._watcher_file_name)
log.DEBUG("creating watcher file: %s" %(self.watcher_file_path))
write_to_file(self.watcher_file_path, "Delete this file to shutdown D2MP\n")
self.watcher.addPath(abspath("."))
self.watcher.directoryChanged.connect(self._watcher_changed_callback)
def _watcher_changed_callback(self, val):
if self._watcher_file_name not in os.listdir(val):
secs = 3
self.show_message("Shutdown", "Watcher file was deleted. D2MP will shotdown in %d seconds." %(secs))
sleep(secs)
self.exit()
def _create_tray_icon(self):
self.tray = QSystemTrayIcon(self)
self.tray.setToolTip("D2Moddin Manager")
self.tray.setIcon(QIcon(SETTINGS['icon']))
traymenu = QMenu()
traymenu.addAction("Restart", self.restart)
traymenu.addAction("Uninstall", self.uninstall)
traymenu.addAction("Preferences", UIManager().open_preferences)
traymenu.addAction("Show mod list", self.show_mod_list)
traymenu.addSeparator()
traymenu.addAction("Exit", self.exit)
self.tray.setContextMenu(traymenu)
self.tray.show()
def restart(self):
python = sys.executable
args = set(sys.argv)
args.add("restart")
os.execl(python, python, *list(sys.argv))
self.exit()
def uninstall(self):
ModManager().delete_mods()
# ModManager().uninstall_d2mp()
self.exit()
def exit(self):
# do some cleanup
return super(SingleApplication, self).exit()
def show_mod_list(self):
self.show_message("Mod List", ModManager().mod_names_as_string())
def show_message_from_socket(self, message):
self.show_message("Server message", message)
def show_error_from_socket(self, message):
self.show_message("Server error", message, QSystemTrayIcon.Critical)
def show_message_from_mod_manager(self, message):
self.show_message("ModManager message", message)
#.........这里部分代码省略.........
示例11: TrayController
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [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(
#.........这里部分代码省略.........
示例12: MainUI
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [as 别名]
#.........这里部分代码省略.........
if signal.is_connected():
connected = True
when_triggered = (lambda sign: lambda:self.please_connect(sign))(signal)
action = QAction(icon, signal.ssid, self, triggered = when_triggered)
signal_actions.append(action)
signal_actions.sort(cmp = action_cmp)
menu.addActions(signal_actions)
self.update_connected_state(connected)
# the bottom part
menu.addSeparator()
menu.addAction(QAction("Share...", self, triggered=self.share_keys))
menu.addAction(QAction("Update Database", self, triggered=self.update_database))
menu.addAction(QAction("Rescan", self, triggered=self.rescan_networks))
menu.addAction(QAction("Quit", self, triggered=self.app_quit))
menu.addAction(QAction("WTF?", self, triggered=self.open_about_dialog))
return menu
def please_connect(self, signal):
logger.debug("Requested connection %s" % signal.ssid)
if not signal.has_password() and signal.encrypted:
self.get_password_for(signal)
else:
self.wifi.connect(signal)
def get_password_for(self, signal):
logger.debug("Need password for %s" % signal.ssid)
d = AddPasswordDialog(self, self.wifi, signal)
d.show()
def share_keys(self):
to_commit = self.wifi.get_known_networks()
to_commit = ShareOwnPasswords(self, to_commit).exec_()
for ap in to_commit:
PM.add_new_ap(ap)
PM.report_success_ap(ap, auto_location = False)
def rescan_networks(self):
self.wifi.force_rescan()
def refresh_menu_items(self, *args):
"""Refresh."""
signals = self.wifi.get_signals()
menu = self.build_menu(signals)
self.sti.setContextMenu(menu)
bssids = [signal.bssid for signal in signals]
GEO.refresh_seen_bssids(bssids)
update_done_signal = QtCore.pyqtSignal()
def update_database(self):
class UpdateFromServerTask(QtCore.QThread):
update_done_signal = self.update_done_signal
def run(self):
PM.get_passwords_from_server()
self.update_done_signal.emit()
self.update_done_signal.connect(self.update_database_done)
self.update_task = UpdateFromServerTask()
self.update_task.start()
def update_database_done(self):
self.refresh_menu_items()
self.update_task = None
def load_icons(self):
self.icons = dict()
self.icons['wefree'] = dict()
self.icons['signals'] = dict()
self.icons['lock-signals'] = dict()
self.icons['lock-signals-unknown'] = dict()
for strength in SIGNALS_IMGS:
self.icons['wefree'][strength] = QIcon(":/imgs/wefree-192.%d.png" % strength)
self.icons['signals'][strength] = QIcon(":/imgs/signals.%d.png" % strength)
self.icons['lock-signals'][strength] = QIcon(":/imgs/lock-signals.%d.png" % strength)
self.icons['lock-signals-unknown'][strength] = QIcon(":/imgs/lock-signals-unknown.%d.png" % strength)
def iconize(self):
"""Show a system tray icon with a small icon."""
self.sti = QSystemTrayIcon(self.icons['wefree'][0], self)
if not self.sti.isSystemTrayAvailable():
logger.warning("System tray not available.")
return
self.refresh_menu_items()
self.sti.show()
def update_connected_state(self, connected):
if connected:
self.sti.setIcon(self.icons['wefree'][100])
else:
self.sti.setIcon(self.icons['wefree'][0])
示例13: MainWindow
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [as 别名]
class MainWindow(QMainWindow):
__connManager = None
__activeClient = -1
def __init__(self, manager, parent = None):
QMainWindow.__init__(self, parent)
self.__activeClient = -1
self.__connManager = manager
self.setWindowTitle(self.tr("Boinc gui"))
self.createActions()
self.createMenu()
self.createMainWin()
self.createTrayIcon()
self.readSettings()
self.statusBar().showMessage(self.tr("Ready"), 3000)
self.queueThread = ProcessQueeueThread(self.__connManager.queue(), self)
self.queueThread.start()
self.__connManager.loadConnections()
self.connect(self.centralWidget, SIGNAL('showStatusBarMsg(QString)'), self.__showStatusBarMsg)
def readSettings(self):
settings = QSettings()
settings.beginGroup("MainWindow")
self.resize(settings.value("size", QVariant(QSize(800, 500))).toSize());
settings.endGroup()
def writeSettings(self):
settings = QSettings()
settings.beginGroup("MainWindow")
settings.setValue("size", QVariant(self.size()));
settings.endGroup()
def closeEvent(self, event):
if self.__trayIcon.isVisible():
event.ignore()
self.hide()
def __showStatusBarMsg(self, msg):
self.statusBar().showMessage(msg, 3000)
def connManager(self):
return self.__connManager
def __del__(self):
self.writeSettings()
self.queueThread.stop()
self.__connManager.queue().put("")
self.queueThread.wait()
def createMainWin(self):
self.centralWidget = mainWidget(self.__connManager)
self.connect(self.centralWidget, SIGNAL('clientChanged(int)'), self.changeClient)
self.setCentralWidget(self.centralWidget)
self.setWindowIcon(QIcon(QPixmap(":boinc.png")))
def createTrayIcon(self):
self.__trayIcon = QSystemTrayIcon(self)
self.__trayIcon.setIcon(QIcon(QPixmap(":boinc.png")))
self.__trayIconMenu = QMenu(self);
self.__trayIconMenu.addAction(self.quitAction)
self.__trayIcon.setContextMenu(self.__trayIconMenu)
self.connect(self.__trayIcon, SIGNAL('activated(QSystemTrayIcon::ActivationReason)'), self.iconActivated)
self.__trayIcon.show()
def iconActivated(self, dovod):
if dovod == QSystemTrayIcon.Trigger:
if self.isVisible():
self.hide()
else:
self.show()
def changeClient(self, client):
self.__activeClient = client
if client == -1:
self.remClientAction.setEnabled(False);
else:
self.remClientAction.setEnabled(True);
def createActions(self):
self.addClientAction = QAction(self.tr("&Add Client"), self)
self.remClientAction = QAction(self.tr("&Remove Client"), self)
self.quitAction = QAction(self.tr("&Quit"), self)
#pridavame klavesove skratky
self.quitAction.setShortcut(QKeySequence(self.tr("Ctrl+Q")))
self.remClientAction.setEnabled(False);
#prepojime akcie so slotmi
self.connect(self.addClientAction, SIGNAL("triggered()"), self.showWizard)
self.connect(self.remClientAction, SIGNAL("triggered()"), self.removeClient)
self.connect(self.quitAction, SIGNAL("triggered()"), qApp, SLOT("quit()"))
def removeClient(self):
if self.__activeClient != -1:
btn = QMessageBox.question(self, self.tr("Remove Client"), self.tr("Are you sure that you want to remove client?"), QMessageBox.Yes|QMessageBox.No)
if btn == QMessageBox.Yes:
self.__connManager.removeConnection(self.__activeClient)
def createMenu(self):
fileMenu = self.menuBar().addMenu(self.tr("&File"))
#.........这里部分代码省略.........
示例14: Example
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [as 别名]
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def openApex(self):
if self.call_id:
webbrowser.open("http://tca-db1.astrakhan.businesscar.ru:8080/apex/f?p=999:1:0::NO:1:P1_ID_CUSTOMER:"+self.customer_id)
def openCrm(self):
if self.customer_id:
webbrowser.open("http://tca-crm/sugar/index.php?action=ajaxui#ajaxUILoc=index.php%3Fmodule%3DCalls%26offset%3D15%26stamp%3D1395146164095815300%26return_module%3DCalls%26action%3DDetailView%26record%3D"+self.call_id)
def initUI(self):
self.icon=QSystemTrayIcon()
r=self.icon.isSystemTrayAvailable()
self.customer_id=""
self.call_id = ""
self.icon.setIcon( QtGui.QIcon('w:\icon.png') )
self.icon.show()
self.setGeometry(350, 30, 640, 480)
self.setWindowIcon(QtGui.QIcon('w:\icon.png'))
self.setWindowTitle(u'CallCenter')
self.show()
self.icon.activated.connect(self.activate)
self.show()
self.icon.menu = QtGui.QMenu()
exitAction = self.icon.menu.addAction(u"Выход")
self.icon.setContextMenu(self.icon.menu)
self.connect(exitAction, QtCore.SIGNAL('triggered()'),QtGui.qApp, QtCore.SLOT('quit()'))
general_groupbox = QtGui.QGroupBox(u"Общая информация",self)
general_groupbox.show()
self.title_label = RedLabel(u"Название:")
surname_label = QtGui.QLabel(u"Фамилия:")
name_label = QtGui.QLabel(u"Имя:")
secondName_label = QtGui.QLabel(u"Отчество:")
clientType_label = RedLabel(u"Тип клиента:")
gender_label = RedLabel(u"Пол:")
burthday_label = RedLabel(u"Дата рождения:")
regDate_label = QtGui.QLabel(u"Дата рег-ции:")
phone_label = QtGui.QLabel(u"Тел.:")
mobilePhone_label = QtGui.QLabel(u"Моб. тел.:")
fax_label = QtGui.QLabel(u"Факс:")
indexCity_label = QtGui.QLabel(u"Индекс\Город:")
address_label = QtGui.QLabel(u"Адрес:")
self.phone_text = LineEdit()
mobilePhone_text = LineEdit()
fax_text = LineEdit()
indexCity_text = LineEdit()
address_text = LineEdit()
self.title_text = LineEdit()
surname_text = LineEdit()
name_text = LineEdit()
secondName_text = LineEdit()
clientType_text = LineEdit()
clientCode_text = LineEdit()
brunch_text = LineEdit()
transport_text = LineEdit()
paymentType_text = LineEdit()
maxSale_text = LineEdit()
gender_text = LineEdit()
burthday_text = LineEdit()
regDate_text = LineEdit()
lastVisit_text = LineEdit()
general_layoutBox = QtGui.QGridLayout(self)
general_layoutBox.setSpacing(10)
general_layoutBox.setColumnMinimumWidth(0,0)
general_layoutBox.addWidget(self.title_label,0,0)
general_layoutBox.addWidget(self.title_text,0,1)
general_layoutBox.addWidget(surname_label)
general_layoutBox.addWidget(surname_text)
general_layoutBox.addWidget(name_label)
general_layoutBox.addWidget(name_text)
general_layoutBox.addWidget(secondName_label)
general_layoutBox.addWidget(secondName_text)
general_layoutBox.addWidget(clientType_label)
general_layoutBox.addWidget(clientType_text)
general_layoutBox.addWidget(gender_label)
general_layoutBox.addWidget(gender_text)
#.........这里部分代码省略.........
示例15: __init__
# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setIcon [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