Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

python - 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
Foo.main()
Foo.main()
Foo.main()

The first call works fine, the second brings forward all hell of warnings, the first of which is

(python:5389): Gtk-CRITICAL **: IA__gtk_container_add: assertion 'GTK_IS_CONTAINER (container)' failed

And the last cause a segmentation fault. What's the problem with my code?

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os
from PyQt4 import Qt
from PyQt4 import QtGui,QtCore

class Foo (QtGui.QWidget):

    def __init__(self,parent=None):
        super(Foo,self).__init__()
        self.setUI()
        self.showMaximized()


    def setUI(self):
        self.setGeometry(100,100,1150,650)
        self.grid = QtGui.QGridLayout()
        self.setLayout(self.grid)

        #For convininece, I set different ui "concepts" in their own function
        self.setInterfaceLine()
        self.setMainText()



    def setMainText(self):
        #the main box, where information is displayed
        self.main_label = QtGui.QLabel('Details')
        self.main_text = QtGui.QLabel()
        self.main_text.setAlignment(QtCore.Qt.AlignTop)
        #Reading the welcome message from file

        self.main_text.setText('')


        self.main_text.setWordWrap(True) #To handle long sentenses
        self.grid.addWidget(self.main_text,1,1,25,8)


    def setInterfaceLine(self):

        #Create the interface section
        self.msg_label = QtGui.QLabel('Now Reading:',self)
        self.msg_line = QtGui.QLabel('commands',self) #the user message label
        self.input_line = QtGui.QLineEdit('',self) #The command line
        self.input_line.returnPressed.connect(self.executeCommand)
        self.grid.addWidget(self.input_line,26,1,1,10)
        self.grid.addWidget(self.msg_label,25,1,1,1)
        self.grid.addWidget(self.msg_line,25,2,1,7)


    def executeCommand(self):
        fullcommand = self.input_line.text() #Get the command
        args = fullcommand.split(' ')
        if fullcommand =='exit':
            self.exit()





    def exit(self):
        #Exit the program, for now, no confirmation
        QtGui.QApplication.quit()



def main():
    app = QtGui.QApplication(sys.argv)
    foo = Foo(sys.argv)
    app.exit(app.exec_())

if __name__ in ['__main__']:
    main()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...