当前位置: 首页>>代码示例>>Python>>正文


Python QSystemTrayIcon.setContextMenu方法代码示例

本文整理汇总了Python中PyQt4.QtGui.QSystemTrayIcon.setContextMenu方法的典型用法代码示例。如果您正苦于以下问题:Python QSystemTrayIcon.setContextMenu方法的具体用法?Python QSystemTrayIcon.setContextMenu怎么用?Python QSystemTrayIcon.setContextMenu使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt4.QtGui.QSystemTrayIcon的用法示例。


在下文中一共展示了QSystemTrayIcon.setContextMenu方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: show

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [as 别名]
def show(main_window):
    """Show a system tray icon with a small icon."""
    _fix_unity_systray()
    icon = QIcon(multiplatform.get_path("encuentro/logos/icon-192.png"))
    sti = QSystemTrayIcon(icon, main_window)
    if not sti.isSystemTrayAvailable():
        logger.warning("System tray not available.")
        return

    def showhide(_):
        """Show or hide the main window."""
        if main_window.isVisible():
            main_window.hide()
        else:
            main_window.show()

    _menu = QMenu(main_window)
    _act = _menu.addAction("Mostrar/Ocultar")
    _act.triggered.connect(showhide)
    _act = _menu.addAction("Acerca de")
    _act.triggered.connect(main_window.open_about_dialog)
    _act = _menu.addAction("Salir")
    _act.triggered.connect(main_window.on_close)
    sti.setContextMenu(_menu)
    sti.show()
开发者ID:Nicogue,项目名称:Encuentro,代码行数:27,代码来源:systray.py

示例2: Tray

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [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()
开发者ID:herlang,项目名称:iosshy,代码行数:62,代码来源:tray.py

示例3: WingedBox

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [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()
开发者ID:ifara,项目名称:wingedbox-client,代码行数:61,代码来源:wingedbox.py

示例4: Tray

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [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()
开发者ID:Kenishi,项目名称:DroidNavi,代码行数:47,代码来源:tray.py

示例5: StartQT4

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [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"没有查到相关记录")
开发者ID:moonxue,项目名称:simpleyoudao,代码行数:47,代码来源:youdao.py

示例6: __init__

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [as 别名]
class Qt4SysTrayIcon:
    def __init__( self ):
        self.snapshots = snapshots.Snapshots()
        self.config = self.snapshots.config
        self.decode = None

        if len( sys.argv ) > 1:
            if not self.config.set_current_profile(sys.argv[1]):
                logger.warning("Failed to change Profile_ID %s"
                               %sys.argv[1], self)

        self.qapp = qt4tools.create_qapplication(self.config.APP_NAME)
        translator = qt4tools.get_translator()
        self.qapp.installTranslator(translator)
        self.qapp.setQuitOnLastWindowClosed(False)

        import icon
        self.icon = icon
        self.qapp.setWindowIcon(icon.BIT_LOGO)

        self.status_icon = QSystemTrayIcon(icon.BIT_LOGO)
        #self.status_icon.actionCollection().clear()
        self.contextMenu = QMenu()

        self.menuProfileName = self.contextMenu.addAction(_('Profile: "%s"') % self.config.get_profile_name())
        qt4tools.set_font_bold(self.menuProfileName)
        self.contextMenu.addSeparator()

        self.menuStatusMessage = self.contextMenu.addAction(_('Done'))
        self.menuProgress = self.contextMenu.addAction('')
        self.menuProgress.setVisible(False)
        self.contextMenu.addSeparator()

        self.btnDecode = self.contextMenu.addAction(icon.VIEW_SNAPSHOT_LOG, _('decode paths'))
        self.btnDecode.setCheckable(True)
        self.btnDecode.setVisible(self.config.get_snapshots_mode() == 'ssh_encfs')
        QObject.connect(self.btnDecode, SIGNAL('toggled(bool)'), self.onBtnDecode)

        self.openLog = self.contextMenu.addAction(icon.VIEW_LAST_LOG, _('View Last Log'))
        QObject.connect(self.openLog, SIGNAL('triggered()'), self.onOpenLog)
        self.startBIT = self.contextMenu.addAction(icon.BIT_LOGO, _('Start BackInTime'))
        QObject.connect(self.startBIT, SIGNAL('triggered()'), self.onStartBIT)
        self.status_icon.setContextMenu(self.contextMenu)

        self.pixmap = icon.BIT_LOGO.pixmap(24)
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)
        self.progressBar.setTextVisible(False)
        self.progressBar.resize(24, 6)
        self.progressBar.render(self.pixmap, sourceRegion = QRegion(0, -14, 24, 6), flags = QWidget.RenderFlags(QWidget.DrawChildren))

        self.first_error = self.config.is_notify_enabled()
        self.popup = None
        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
#.........这里部分代码省略.........
开发者ID:heysion,项目名称:backintime,代码行数:103,代码来源:qt4systrayicon.py

示例7: PigeonFeather

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [as 别名]
class PigeonFeather(QMainWindow):
    """Main class for the application, inherits class genrated from pyuic"""

    def __init__(self, parent=None):
        super(PigeonFeather, self).__init__(parent)

        # Check that environment supports systemtray
        if not QSystemTrayIcon.isSystemTrayAvailable():
            print('FATAL: There is no system tray')
            sys.exit(1)

        # Make sure that we can load an icon list
        try:
            with open('code2iconlist.pkl', 'rb') as iconList:
                self.codeToIconList = pickle.load(iconList)
        except (IOError, pickle.PickleError):
            print('FATAL: Could not not load code2iconlist')
            sys.exit(1)

        # See if balloon messages are supported
        #print('Desktop support balloon messages = ' + \
        #    str(QSystemTrayIcon.supportsMessages()))

        # Set the user config fle
        self.USER_CONFIG = os.path.expanduser('~/.pigeonfeather')

        # Load preferences
        self.loadConfig()

        # Class properties
        self.trayIcon = QSystemTrayIcon(self)

        # Weather Dialog and Configure Dialog
        self.weatherDialog = WeatherDialog(self)
        self.configureDialog = ConfigureDialog(self)

        # Set up the application
        self.setup()

    def setup(self):
        """Setup and start the application"""
        # Connect some slots

        # Icon is clicked
        self.connect(self.trayIcon, \
            SIGNAL('activated(QSystemTrayIcon::ActivationReason)'), \
            self.trayIconClicked)

        # Connnect slot emitted from CnfigureDialog to update preferences
        self.connect(self.configureDialog, SIGNAL('ConfigureDialogOk'), \
            self.saveConfig)

        # Set an initial icon for tray and weather dialog
        self.setTrayIcon(QIcon('images/22/dunno.png'))
        self.weatherDialog.labelIcon.setPixmap(QPixmap('images/64/dunno.png'))

        # Set the menu
        self.trayIcon.setContextMenu(self.createMenu())

        # Setup the config dialog with values loaded from config
        woeid = self.config.get('main', 'woeid')

        # If woeid is not valid set a default and use that
        try:
            self.configureDialog.setWoeid(woeid)
        except ValueError as ve:
            self.config.set('main', 'woeid', '2408842')
            self.configureDialog.setWoeid('2408842')

        # Set temperature units
        if self.config.get('units', 'temperature') == 'fahrenheit':
            self.configureDialog.setTemperature('fahrenheit')
        else:
            self.configureDialog.setTemperature('celcius')

        # Set distance units
        if self.config.get('units', 'distance') == 'km':
            self.configureDialog.setDistance('km')
        else:
            self.configureDialog.setDistance('mi')

        # Set wind units
        if self.config.get('units', 'wind') == 'kph':
            self.configureDialog.setWind('kph')
        else:
            self.configureDialog.setWind('mph')

        # Set pressure units
        if self.config.get('units', 'pressure') == 'mb':
            self.configureDialog.setPressure('mb')
        else:
            self.configureDialog.setPressure('in')

        # Start getWeather thread with Id from config
        # Connect two slots for the two signals emitted from thread
        self.getWeatherThread = GetWeatherQThread(self.config.get( \
            'main', 'woeid'))
        self.getWeatherThread.start()

        self.connect(self.getWeatherThread, SIGNAL('WeatherUpdate'), \
#.........这里部分代码省略.........
开发者ID:billyrayvalentine,项目名称:python-pigeonfeather,代码行数:103,代码来源:PigeonFeather.py

示例8: GuiApplicationLinux

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [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)
开发者ID:amitahire,项目名称:bitfighter,代码行数:93,代码来源:bitfighter_notifier.py

示例9: __init__

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [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(
#.........这里部分代码省略.........
开发者ID:juancarlospaco,项目名称:pyqt_app_template,代码行数:103,代码来源:pyqt_app_template.py

示例10: MainWindow

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [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
#.........这里部分代码省略.........
开发者ID:dmzkrsk,项目名称:wol-tray,代码行数:103,代码来源:run.py

示例11: Application

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [as 别名]
class Application(QApplication):
    def __init__(self, *args, **kwargs):
        super(Application, self).__init__(*args, **kwargs)

        self.application_path = dirname(__file__)

        self.settings = Settings()

        if Settings.config().debug:
            basicConfig(level=DEBUG)

        self.setQuitOnLastWindowClosed(Settings.config().debug)

        self.history = History(
            tray_notify=self.tray_notify
        )

        self.aboutToQuit.connect(self.settings.settings_save)

        self.create_actions()
        self.create_tray_icon()

    def create_actions(self):
        self.action_take_screenshot = QAction(
            'Take a screenshot',
            self,
            triggered=self.take_screenshot
        )
        self.action_quit = QAction(
            'Quit',
            self,
            triggered=qApp.quit
        )

    def create_tray_icon(self):
        self.menu_tray = QMenu()
        self.menu_tray.addAction(self.action_take_screenshot)
        self.menu_tray.addSeparator()
        self.menu_tray.addAction(self.action_quit)

        self.icon_tray = QSystemTrayIcon(
            QIcon(join(
                self.application_path,
                'icons/camera.png'
            ))
        )
        self.icon_tray.setContextMenu(self.menu_tray)
        self.icon_tray.activated.connect(self.tray_icon_activated)
        self.icon_tray.show()

    def tray_icon_activated(self, reason):
        if reason != QSystemTrayIcon.Trigger:
            return
        self.take_screenshot()

    def take_screenshot(self):
        self.selecter = SelectArea(
            doneSignal=self.history.start_new_upload
        )

    def tray_notify(self, message):
        self.icon_tray.showMessage(
            'Screenshot',
            message,
            QSystemTrayIcon.Information,
            3000
        )
开发者ID:alexey-grom,项目名称:qt-screenshoter,代码行数:69,代码来源:main.py

示例12: LeapWindow

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [as 别名]

#.........这里部分代码省略.........
        """
        creates actions to be binded to tray icon
        """
        self.connectVPNAction = QAction("Connect to &VPN", self,
                                        triggered=self.hide)
        # XXX change action name on (dis)connect
        self.dis_connectAction = QAction("&(Dis)connect", self,
                                         triggered=self.start_or_stopVPN)
        self.minimizeAction = QAction("Mi&nimize", self,
                                      triggered=self.hide)
        self.maximizeAction = QAction("Ma&ximize", self,
                                      triggered=self.showMaximized)
        self.restoreAction = QAction("&Restore", self,
                                     triggered=self.showNormal)
        self.quitAction = QAction("&Quit", self,
                                  triggered=self.cleanupAndQuit)

    def createTrayIcon(self):
        """
        creates the tray icon
        """
        self.trayIconMenu = QMenu(self)

        self.trayIconMenu.addAction(self.connectVPNAction)
        self.trayIconMenu.addAction(self.dis_connectAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.minimizeAction)
        self.trayIconMenu.addAction(self.maximizeAction)
        self.trayIconMenu.addAction(self.restoreAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.quitAction)

        self.trayIcon = QSystemTrayIcon(self)
        self.trayIcon.setContextMenu(self.trayIconMenu)

    def createLogBrowser(self):
        """
        creates Browser widget for displaying logs
        (in debug mode only).
        """
        self.loggerBox = QGroupBox()
        logging_layout = QVBoxLayout()
        self.logbrowser = QTextBrowser()

        startStopButton = QPushButton("&Connect")
        startStopButton.clicked.connect(self.start_or_stopVPN)
        self.startStopButton = startStopButton

        logging_layout.addWidget(self.logbrowser)
        logging_layout.addWidget(self.startStopButton)
        self.loggerBox.setLayout(logging_layout)

        # status box

        self.statusBox = QGroupBox()
        grid = QGridLayout()

        self.updateTS = QLabel('')
        self.status_label = QLabel('Disconnected')
        self.ip_label = QLabel('')
        self.remote_label = QLabel('')

        tun_read_label = QLabel("tun read")
        self.tun_read_bytes = QLabel("0")
        tun_write_label = QLabel("tun write")
        self.tun_write_bytes = QLabel("0")
开发者ID:isislovecruft,项目名称:leap_client,代码行数:70,代码来源:mainwindow.py

示例13: SingleApplication

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [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)
#.........这里部分代码省略.........
开发者ID:BloodyD,项目名称:D2ModdinPyClient,代码行数:103,代码来源:main.py

示例14: LunchinatorGuiController

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [as 别名]

#.........这里部分代码省略.........
        if not icon:
            icon = QIcon(icon_file)
        
        self.statusicon.setIcon(icon)
        
    def createTrayIcon(self):
        if platform.linux_distribution()[0] == "Ubuntu":
            if not os.path.exists('/usr/share/icons/ubuntu-mono-light/status/24/lunchinator.svg') or \
               not os.path.exists('/usr/share/icons/ubuntu-mono-dark/status/24/lunchinator.svg'):
                result = QMessageBox.question(self.mainWindow,
                                              "Install Icons",
                                              "Do you want to install the Lunchinator icons into the Ubuntu theme folders? You will have to enter your sudo password.",
                                              buttons=QMessageBox.Yes | QMessageBox.No,
                                              defaultButton=QMessageBox.Yes)
                if result == QMessageBox.Yes:
                    if subprocess.call(['gksu', get_settings().get_resource('bin', 'install-lunch-icons.sh') + ' lunchinator']) == 0:
                        getCoreLogger().info("restarting after icons were installed")
                        restart(getCoreLogger())
                        return False
                    else:
                        QMessageBox.critical(self.mainWindow,
                                             "Error installing icons",
                                             "The icons were not installed, there was an error.",
                                             buttons=QMessageBox.Ok,
                                             defaultButton=QMessageBox.Ok)
                        getCoreLogger().info("icons were not installed because of an error")
        
        # initialize tray icon
        self.statusicon = QSystemTrayIcon(self.mainWindow)
        # _highlightIcon sets the default icon
        self._highlightIcon()
        contextMenu = self.init_menu(self.mainWindow)
        self.statusicon.activated.connect(self.trayActivated)
        self.statusicon.setContextMenu(contextMenu)
        self.statusicon.show()
        return True
        
    @loggingSlot(QSystemTrayIcon.ActivationReason)
    def trayActivated(self, reason):
        if getPlatform() == PLATFORM_MAC:
            # Trigger is sent even though the context menu is shown.
            return
        if reason == QSystemTrayIcon.Trigger:
            self.statusicon.contextMenu().popup(QCursor.pos())
        
    def _coldShutdown(self, exitCode=0):
        # before exiting, process remaining events (e.g., pending messages like HELO_LEAVE)
        QCoreApplication.processEvents()
        QCoreApplication.exit(exitCode)
        self._shuttingDown = True
        
    def isShuttingDown(self):
        return self._shuttingDown
        
    def quit(self, exitCode=0):
        if self.mainWindow is not None:
            self.mainWindow.close()
        if self.settingsWindow is not None:
            self.settingsWindow.close()
        
        if self.serverThread != None and not sip.isdeleted(self.serverThread) and self.serverThread.isRunning():
            self.serverThread.finished.disconnect(self.serverFinishedUnexpectedly)
            get_server().stop_server()
            getCoreLogger().info("Waiting maximal 30s for server to stop...")
            # wait maximal 30s 
            if self.serverThread.wait(30000):
开发者ID:hannesrauhe,项目名称:lunchinator,代码行数:70,代码来源:gui_controller.py

示例15: MainWindow

# 需要导入模块: from PyQt4.QtGui import QSystemTrayIcon [as 别名]
# 或者: from PyQt4.QtGui.QSystemTrayIcon import setContextMenu [as 别名]
class MainWindow(QMainWindow):
    def __init__(self, config):
        super(MainWindow, self).__init__()
        self.config = Config(config)
        db = Database(self.config.getConnectionString())
        db.create()
        self.hosts = Hosts(db)

        # menu used for each host
        self.hostMenu = QMenu()
        self.hostMenu.addAction(QIcon(":/ico/edit.svg"), "Edit", self.editHost)
        self.hostMenu.addAction(QIcon(":/ico/remove.svg"), "Delete", self.deleteHost)
        actions.addActionWithScreenChose(
            self.hostMenu, self.connectFrameless, ":/ico/frameless.svg", "Connect frameless"
        )

        # setup main window
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # when top level changed, we changing dock title bar
        self.dockWidgetTileBar = DockWidgetTitleBar()
        self.ui.hostsDock.setTitleBarWidget(self.dockWidgetTileBar)
        self.ui.hostsDock.topLevelChanged.connect(self.dockLevelChanged)

        # set global menu
        self.globalMenu = QMenu()
        self.globalMenu.addAction(QIcon(":/ico/add.svg"), "Add host", self.addHost)
        # disable menu indicator
        self.ui.menu.setStyleSheet("QPushButton::menu-indicator {image: none;}")
        self.positionMenu = QMenu("Dock position")
        self.positionMenu.addAction("Left", lambda: self.setDockPosition(Qt.LeftDockWidgetArea))
        self.positionMenu.addAction("Right", lambda: self.setDockPosition(Qt.RightDockWidgetArea))
        self.positionMenu.addAction("Float", self.setDockFloat)
        self.globalMenu.addMenu(self.positionMenu)
        self.globalMenu.addAction("Change tray icon visibility", self.changeTrayIconVisibility)
        self.globalMenu.addAction("Quit", self.close)
        self.ui.menu.setMenu(self.globalMenu)

        # set events on hosts list
        self.ui.hostsList.itemDoubleClicked.connect(self.slotConnectHost)
        self.ui.hostsList.itemClicked.connect(self.slotShowHost)
        self.ui.hostsList.customContextMenuRequested.connect(self.slotShowHostContextMenu)

        # set tab widget
        self.tabWidget = MyTabWidget()
        self.setCentralWidget(self.tabWidget)

        # set tray icon
        self.tray = QSystemTrayIcon(QIcon(":/ico/myrdp.svg"))
        self.tray.activated.connect(self.trayActivated)

        self.trayMenu = QMenu()
        self.trayMenu.addAction("Hide tray icon", self.changeTrayIconVisibility)
        self.trayMenu.addAction("Quit", self.close)

        self.tray.setContextMenu(self.trayMenu)

        # host list
        self.ui.filter.textChanged.connect(self.setHostList)
        self.setHostList()
        self.restoreSettings()

    def trayActivated(self, reason):
        if reason != QSystemTrayIcon.Trigger:
            return
        if self.isVisible():
            self.hide()
        else:
            self.show()
            self.activateWindow()

    def changeTrayIconVisibility(self):
        if self.tray.isVisible():
            self.tray.hide()
            if not self.isVisible():
                self.show()
        else:
            self.tray.show()

    def setDockPosition(self, dockWidgetArea):
        if self.ui.hostsDock.isFloating():
            self.ui.hostsDock.setFloating(False)
        self.addDockWidget(dockWidgetArea, self.ui.hostsDock)

    def setDockFloat(self):
        if self.ui.hostsDock.isFloating():
            return
        # default title bar must be set before is float because sometimes window make strange crash
        self.ui.hostsDock.setTitleBarWidget(None)
        self.ui.hostsDock.setFloating(True)

    def dockLevelChanged(self, isFloating):
        if isFloating:
            # changing title bar widget if is not none, probably true will be only once on start with saved float state
            if self.ui.hostsDock.titleBarWidget():
                self.ui.hostsDock.setTitleBarWidget(None)
        else:
            self.ui.hostsDock.setTitleBarWidget(self.dockWidgetTileBar)

#.........这里部分代码省略.........
开发者ID:szatanszmatan,项目名称:myrdp,代码行数:103,代码来源:mainwindow.py


注:本文中的PyQt4.QtGui.QSystemTrayIcon.setContextMenu方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。