# Signals need to be contained in a QObject or subclass in order to be correctly # initialized. # classSignaller (QtCore.QObject): signal=Signal( str, logging .LogRecord) # # Output to a Qt GUI is only supposed to happen on the main thread. So, this # handler is designed to take a slot function which is set up to run in the main # thread. In this example, the function takes a string argument which is a # formatted log message, and the log record which generated it. The formatted # string is just a convenience - you could format a string for output any way # you like in the slot function itself. # # You specify the slot function to do whatever GUI updates you want. The handler # doesn't know or care about specific UI elements. # classQtHandler (logging .Handler): def __init__ (self, slotfunc, *args,**kwargs): super() .__init__ (*args,**kwargs) self.signaller=Signaller() self.signaller.signal.connect(slotfunc) def emit(self, record): s =self.format(record) self.signaller.signal.emit(s, record) # # This example uses QThreads, which means that the threads at the Python level # are named something like "Dummy-1". The function below gets the Qt name of the # current thread. # def ctname(): return QtCore.QThread .currentThread() .objectName() # # Used to generate random levels for logging. # LEVELS =(logging .DEBUG, logging .INFO, logging.WARNING, logging .ERROR, logging.CRITICAL) # # This worker class represents work that is done in a thread separate to the # main thread. The way the thread is kicked off to do work is via a button press # that connects to a slot in the worker. # # Because the default threadName value in the LogRecord isn't much use, we add # a qThreadName which contains the QThread name as computed above, and pass that # value in an "extra" dictionary which is used to update the LogRecord with the # QThread name. # # This example worker just outputs messages sequentially, interspersed with # random delays of the order of a few seconds. # classWorker (QtCore.QObject): @Slot () def start(self): extra ={ 'qThreadName ': ctname() } logger.debug( 'Started work', extra =extra) i =1 (continued from previous page) (continues on next page) 44