Найти - Пользователи
Полная версия: Как использовать диалоговые окна в PyQt, если программа работает в цикле?
Начало » GUI » Как использовать диалоговые окна в PyQt, если программа работает в цикле?
1
Xyanide
import sys
import types
from collections import OrderedDict
from PyQt4 import QtGui, QtCore
class ProgramTray(QtCore.QThread):
    def __init__(self, icon):
        QtCore.QThread.__init__(self)
        self.menu = QtGui.QMenu()
        self.icon = QtGui.QSystemTrayIcon(QtGui.QIcon(icon))
        self.flag_exit = True
        # Пользовательсеий код работающий в отдельном потоке в трее.
        self.code = None
    def run(self):
        if isinstance(self.code, types.MethodType) \
            or isinstance(self.code, types.FunctionType):
            self.code()
        else:
            QtGui.QApplication.quit()
            raise TypeError, "Parameter code has to be a function or class " \
                             "method"
    def stop(self):
        self.flag_exit = False
    def setMenu(self, menu=None):
        """Устанавливает пункты меню на иконке в трее"""
        if not menu:
            menu = []
        # Создаем коллекцию не отсортированых элементов.
        collection = OrderedDict(menu)
        items = collection.keys()  # [имена пунктов]
        functions = collection.values()  # [функции. соотвествующие пунктам]
        for i, item in enumerate(items):
            function = functions[i]  
            if isinstance(function, types.MethodType) \
                or isinstance(function, types.FunctionType):
                self.menu.addAction(QtGui.QAction(item, self,
                                    triggered=function))
        self.quitAction = QtGui.QAction("Exit", self,
                                        triggered=self.stop)
        self.menu.addAction(self.quitAction)
        self.icon.setContextMenu(self.menu)
if __name__ == "__main__":
    import time
    def yourCode():
        while programTray.flag_exit:
            time.sleep(1)
            print "Work your code ..."
        QtGui.QApplication.quit()
    app = QtGui.QApplication(sys.argv)
    programTray = ProgramTray("./icon.png")
    programTray.code = yourCode
    programTray.setMenu()
    programTray.icon.show()
    programTray.start()
    app.exec_()

Подскажите, как я могу вызывать диалоговые окна QtGui.QMessageBox.Information, QtGui.QMessageBox.Critical, QtGui.QMessageBox.Question, QtGui.QMessageBox.Warning и QtGui.QFileDialog.Options в функции yourCode?
alex925
Ну примерно так:
import sys
import time
from PyQt4 import QtGui, QtCore
 
 
class WorkThread(QtCore.QThread):
    def __init__(self, func):
        super().__init__()
        self.func = func
        self.running = True
 
    def run(self):
        count = 0
        while self.running:
            self.func()
            count += 1
            if count == 4:
                self.emit(QtCore.SIGNAL('tip(QString)'), 'Событие наступило')
 
 
class ProgramTray(QtGui.QSystemTrayIcon):
    def __init__(self, icon, working):
        super().__init__(QtGui.QIcon(icon))
        self.working = working
        self.menu = QtGui.QMenu()
        self.setContextMenu(self.menu)
        self.createAction()
        self.connect(working, QtCore.SIGNAL('tip(QString)'), self.show_tip, QtCore.Qt.QueuedConnection)
 
    def createAction(self):
        """
        Устанавливает пункты меню на иконке в трее
        """
        self.quitAction = QtGui.QAction("Exit", self)
        self.connect(self.quitAction, QtCore.SIGNAL('triggered()'), QtGui.qApp, QtCore.SLOT('quit()'))
        self.menu.addAction(self.quitAction)
 
        self.stopAction = QtGui.QAction("Stop thread", self)
        self.connect(self.stopAction, QtCore.SIGNAL('triggered()'), self.stop)
        self.menu.addAction(self.stopAction)
 
    def stop(self):
        self.working.running = False
 
    def show_tip(self, data):
        messages = QtGui.QMessageBox(QtGui.QMessageBox.Information, 'Уведомление', data,
                                         QtGui.QMessageBox.Ok)
        messages.exec_()
 
 
def yourCode():
    time.sleep(1)
    print("Work your code ...")
 
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    thread = WorkThread(yourCode)
    tray = ProgramTray('./icon.png', thread)
    thread.start()
    tray.show()
    app.exec_()
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB