Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple windows in PyQt4?

Tags:

python

pyqt4

I've just begun using pyqt4. I followed a tutorial (http://zetcode.com/tutorials/pyqt4/) One thing that puzzles me is this part:

def main():
    app = QtGui.QApplication(sys.argv)
    ex = GUI()
    sys.exit(app.exec())

And the reason for this I explain here:

I have made a small program that opens four more windows except for the first main window. So I tried to replicate what I saw worked with main-window and created a class for every new window and tried to do like with the above. Currently it looks like this:

def main2():
    #app = QtGui.QApplication(sys.argv)
    ex2 = Settings()
    sys.exit(app.exec())

As you can see I have modified it. If I left the first line in the function uncommented the program would crash. I tried to do without the sys.exit(app.exec_())-part but that would only make the new window close milliseconds after it showed. This way though, everything runs and works. Only that in the command window, an error message displays. I don't know how to fix this, since I cannot remove the last line, and I dont't know what to replace "app" with.

I know I'm probably doing the new windows wrong from the beginning, but I don't know how to make these windows open from the original window in any other way. I haven't been able to get anything else to work, and this at least runs and works right now. So the only problem is error messages in the prompt, it would be nice to get rid of them :)

Thanks for any help (complicated and easy ones)!

Forgot to mention, I made the classes start like this:

class GUI(QtGui.QMainWindow):
    def __init__(self):
        super(GUI, self).__init__()
        self.initUI()

and

class Settings(QtGui.QWidget):
    def __init__(self):
        super(Settings, self).__init__()
        ...here goes some more...
        self.initUI2()

and I open Settings-window by calling main2()

like image 661
right_there Avatar asked Apr 25 '13 14:04

right_there


1 Answers

You must create one and only one QApplication in your program.

Keep in mind that GUI programming is event-driven, you first declare widgets and then run the main loop with app.exec(), when the user quit your application, app.exec() returns.

The QApplication purpose is to handle user events and propagate them to your code with Qt signals. I suggest you check Qt documentation, it's very complete, even if it's targetting C++ programmers.

So for instance, a way to create two widgets would be:

def main():
    app = QtGui.QApplication(sys.argv)

    ex = QtGui.QWidget()
    ex.show()
    ex2 = QtGui.QWidget()
    ex2.show()

    sys.exit(app.exec())
like image 194
Julien Avatar answered Sep 22 '22 12:09

Julien