views:

644

answers:

3

I have a PyQt program used to visualize some python objects. I would like to do display multiple objects, each in its own window.

What is the best way to achieve multi-window applications in PyQt4?

Currently I have the following:

from PyQt4 import QtGui

class MainWindow(QtGui.QMainWindow):
    windowList = []

    def __init__(self, animal):
     pass

    def addwindow(self, animal)
     win = MainWindow(animal)
     windowList.append(win)

if __name__=="__main__":
    import sys

    app = QtGui.QApplication(sys.argv)

    win = QMainWindow(dog)
    win.addWindow(fish)
    win.addWindow(cat)

    app.exec_()

However, this approach is not satisfactory, as I am facing problems when I try to factor out the MultipleWindows part in its own class. For example:

class MultiWindows(QtGui.QMainWindow):
    windowList = []

    def __init__(self, param):
     raise NotImplementedError()

    def addwindow(self, param)
     win = MainWindow(param) # How to call the initializer of the subclass from here?
     windowList.append(win)

class PlanetApp(MultiWindows):
    def __init__(self, planet):
     pass

class AnimalApp(MultiWindows):
    def __init__(self, planet):
     pass

if __name__=="__main__":
    import sys

    app = QtGui.QApplication(sys.argv)

    win = PlanetApp(mercury)
    win.addWindow(venus)
    win.addWindow(jupiter)

    app.exec_()

The above code will call the initializer of the MainWindow class, rather than that of the appropriate subclass, and will thus throw an exception.

How can I call the initializer of the subclass? Is there a more elegant way to do this?

A: 

In order to reference the subclass that is inheriting the super-class from inside the super-class, I am using self.__class__(), so the MultiWindows class now reads:

class MultiWindows(QtGui.QMainWindow):
windowList = []

def __init__(self, param):
    raise NotImplementedError()

def addwindow(self, param)
    win = self.__class__(param)
    windowList.append(win)
celil
+1  A: 
mandel
A: 

I'm interested in this question too. I'm afraid mandel's code doesn't work for me (using PyQt4). After giving a parameter argument to the call to MultiWindows() (i.e. windows = MultiWindows("myparam")) I still get an error: windows.addWindow(jupiter) AttributeError: addWindow

I apologize in advance for being an absolute beginner, not just with python but with OO programming in general.

Cheers Gib

Gib