Printing to a "log screen" in a multi-module QT app

Boudewijn Rempt boud at rempt.xs4all.nl
Wed Feb 27 16:11:22 EST 2002


Anders Schneiderman <schneida at seiu.org> wrote:
> I'm writing an application using QT.  Right now when I want to use the
> equivalent of "print", I call a method called "log" that's defined in
> the main class in my main module:

> def log(self, msg):
>    try:
>       self.logArea.insertline(msg, -1)
>    except:
>       self.logArea.insertline(str(msg), -1)

> To call it in other classes that are in other modules of the app, I
> pass "log" to the new class.  For ex:

> class CodeEditor:
>    def __init__ (self, log, ...)
>        self.log = log

> Is there a cleaner way to do this?  For example, is there a way to
> redefine the "print" command?  Whatever solution I come up with, the
> command to print has to be short;  "self.logObject.log('File
> successfully updated')" is too much of a pain.  Any suggestions?

As a random, untested, and wild idea: create an object that allows
reading and writing. Have this object be a class member in a module:
import that class. Have the apps write to the object; have your log
window read from that object periodically, using QTimer.

Another equally wild idea: add a log function to the QApplication class,
which you can access with qApp. Have that function emit a signal, which
is connected to a slot in your log displayer.

You could, of course, also have a log function in _all_ your classes
(perhaps via an add-in class), which once establishes the ultimate parent
QMainWindow, and writes to the single logwindow of that object.

Or you could emit a log signal from all your classes, with the message as
the payload, and connect your objects to the logwindow when creating them.

But passing the logwindow to all your classes should be quite unnecessary,
since, in essence, it's an object shared by all your other objects, much
like the configuration object in the example application in my book. (Which
is now available in paper format from opendocs.org -- yay!)

-- 

Boudewijn Rempt  | http://www.valdyas.org 



More information about the Python-list mailing list