Skip to content Skip to sidebar Skip to footer

Loading A Pyqt Application Multiple Times Cause Segmentation Fault

I have a file, Foo.py which holds the code below. When I run the file from command line using, python Foo.py everything works. However, if I use CLI of python python import Foo Fo

Solution 1:

I'm able to reproduce in Python 3 but not Python 2.

It's something about garbage collection and multiple QApplications. Qt doesn't expect multiple QApplications to be used in the same process, and regardless of whether it looks like you're creating a new one every time, the old one is living on somewhere in the interpreter. On the first run of your main() method, You need to create a QApplication and prevent it from being garbage collected by storing it somewhere like a module global or an attribute to a class or instance in the global scope that won't be garbage collected when main() returns.

Then, on subsequent runs, you should access the existing QApplication instead of making a new one. If you have multiple modules that might need a QApplication but you don't want them to have to coordinate, you can access an existing instance with QApplication.instance(), and then only instantiate one if none exists.

So, changing your main() method to the following works:

def main():
    global app
    app = QtGui.QApplication.instance()
    if app is None:
        app = QtGui.QApplication(sys.argv)
    foo = Foo(sys.argv)
    app.exit(app.exec_())

It's odd you have to keep a reference to ensure the QApplication is not garbage collected. Since there is only supposed to be one per process, I would have expected it to live forever even if you don't hold onto a reference to it. That's what seems to happen in Python 2. So ideally the global app line would not be needed above, but it's there to prevent this garbage collection business.

We're kind of stuck in the middle about how immortal this QApplication object is ... it's too long lived for you to be able to use a new one each time, but not long-lived enough on its own for you to re-use it each run without having to prevent its garbage collection by holding onto a reference. This might be bug in PyQt, which probably ought to do the reference holding for us.

Solution 2:

There must be only on QApplication instance in one process. GUI frameworks are not prepared for multi-application mode.

Solution 3:

I can't actually reproduce the problem, which at least shows there's nothing fundamentally wrong with the code.

The problem is probably caused by some garbage-collection issues when the main function returns (the order of deletion can be unpredictable).

Try putting del foo after the event-loop exits.

Post a Comment for "Loading A Pyqt Application Multiple Times Cause Segmentation Fault"