PyQt: вызов приложения TrayMinimized - PullRequest
0 голосов
/ 15 декабря 2009

У меня есть приложение, которое сворачивается в трей (показывает значок), когда пользователь закрывает его. Что мне нужно знать, так это как мне перезвонить с помощью комбинации клавиш, например, Ctrl + Alt + Something. На самом деле я перезваниваю, когда дважды щелкаю по нему, но было бы неплохо сделать то же самое при нажатии клавиши. Вот часть кода:

# -*- coding: utf-8 -*-

"""The user interface for our app"""

import os,sys
import ConfigParser

# Import Qt modules
from PyQt4 import QtCore,QtGui

# Import the compiled UI module
from octo import Ui_Form
CFG_PATH = "etc/config.list"   #Config File Path
#config.list vars DEFAULT Values
ClipCount = 8
Static = ""
window = None


# Create a class for our main window
class Main(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)        
        # This is always the same
        self.ui=Ui_Form()
        self.ui.setupUi(self)
        # Window Icon
        icon = QtGui.QIcon("SSaver.ico")    
        self.setWindowIcon(icon)
        self.setWindowTitle("Octopy")     
        # Set the timer =)      
        self.timer = self.startTimer(1000) #self.killTimer(self.timer)
        # Clipboard Counter
        self.counter = 0
        #Last trapped clipboard
        self.LastClip = ""           
        self.tentacles = [""] * 8  

        self.cmd = []
        self.cmd.append(self.ui.cmd_1)
        self.cmd.append(self.ui.cmd_2)
        self.cmd.append(self.ui.cmd_3)
        self.cmd.append(self.ui.cmd_4)
        self.cmd.append(self.ui.cmd_5)
        self.cmd.append(self.ui.cmd_6)                                        
        self.cmd.append(self.ui.cmd_7)
        self.cmd.append(self.ui.cmd_8)                

## Events ##          
    def on_cmd_8_pressed(self): #Clear
        for i in range(0,7):
            self.tentacles[i] = ""            
            self.cmd[i].setText(self.tentacles[i])  


    def on_cmd_1_pressed(self):
        t = self.ui.cmd_1.text()
        self.setClp(t)

    def on_cmd_2_pressed(self):
        t = self.ui.cmd_2.text()
        self.setClp(t)

    def on_cmd_3_pressed(self):
        t = self.ui.cmd_3.text()
        self.setClp(t)

    def on_cmd_4_pressed(self):
        t = self.ui.cmd_4.text()
        self.setClp(t)

    def on_cmd_5_pressed(self):
        t = self.ui.cmd_5.text()
        self.setClp(t)

    def on_cmd_6_pressed(self):
        t = self.ui.cmd_6.text()
        self.setClp(t)

    def on_cmd_7_pressed(self):                        
        t = self.ui.cmd_7.text()
        self.setClp(t)

    def hideEvent(self,event): # Capture close and minimize events
        pass

    def keyPressEvent(self,ev):
        if ev.key() == 16777216:
            self.hide()

    def showEvent(self,ev):
        self.fillClp()       

    def timerEvent(self,ev):
        c = self.getClp()           
        if c:                        
            #print c, self.counter 
            self.tentacles[self.counter] = c
            if self.counter < 7:
                self.counter += 1
            else:
                self.counter = 0

            self.fillClp()

## Functions ##
    def fillClp(self):
        for i in range(0,7):
            self.cmd[i].setText(self.tentacles[i])   

    def getClp(self):
        clp = QtGui.QApplication.clipboard() 
        c = clp.text()                        
        if self.LastClip != c:
            self.LastClip = c
            return c
        else:
            return None

    def setClp(self, t):               
        clp = QtGui.QApplication.clipboard() 
        clp.setText(t)        


class SystemTrayIcon(QtGui.QSystemTrayIcon):
    def __init__(self, icon, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, icon, parent)
        menu = QtGui.QMenu(parent)                
        # Actions
        self.action_quit = QtGui.QAction("Quit", self)
        self.action_about = QtGui.QAction("About Octopy", self)
        # Add actions to menu
        menu.addAction(self.action_about)
        menu.addSeparator()
        menu.addAction(self.action_quit)
        # Connect menu with signals
        self.connect(self.action_about, QtCore.SIGNAL("triggered()"), self.about)       
        self.connect(self.action_quit, QtCore.SIGNAL("triggered()"), self.quit) 
        # Other signals
        traySignal = "activated(QSystemTrayIcon::ActivationReason)"
        QtCore.QObject.connect(self, QtCore.SIGNAL(traySignal), self.icon_activated)
        # Create Menu               
        self.setContextMenu(menu)

    def quit(self):
        w = QtGui.QWidget()
        reply = QtGui.QMessageBox.question(w, 'Confirm Action',"Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:           
            QtGui.QApplication.quit()

    def about(self):            
        w = QtGui.QWidget()
        QtGui.QMessageBox.information(w, 'About', "Octopy Multi-Clipboard Manager\n Developed by mRt.")

    def icon_activated(self, reason):
        if reason == QtGui.QSystemTrayIcon.DoubleClick:
            window.show()
        else:
            print "otro"     


def main():
    # Again, this is boilerplate, it's going to be the same on 
    # almost every app you write
    app = QtGui.QApplication(sys.argv)        
    # TrayIcon
    w = QtGui.QWidget()
    icon = QtGui.QIcon("SSaver.ico")          
    trayIcon = SystemTrayIcon(icon, w)
    trayIcon.show()    
    trayIcon.setToolTip("Octopy Multi-Clipboard Manager")    
    # Main Window
    global window    
    window=Main()
    window.show()    
    window.setWindowTitle("Octopy")
    app.setQuitOnLastWindowClosed(0)
    sys.exit(app.exec_())    


def readIni():
    cfg = ConfigParser.ConfigParser()
    cfg.read(CFG_PATH)
    ClipCount = int(cfg.get("Other","ClipCount"))
    Static = cfg.get("Other","Static")
    clip = [""] * int(ClipCount+1)    


if __name__ == "__main__":
    readIni()
    main()

Вся программа размещена на Google: http://code.google.com/p/octopys/downloads/list

1 Ответ

1 голос
/ 15 декабря 2009

Чтобы нажатие клавиши обрабатывалось вашим приложением, когда оно не сфокусировано на клавиатуре, необходимо установить глобальное сочетание клавиш. Qt не поддерживает это, но Qxt, библиотека расширения Qt, поддерживает. Увидеть http://doc.libqxt.org/0.5.0/classQxtGlobalShortcut.html. Я не знаю, существуют ли привязки PyQt для Qxt.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...