PyQT exit error in SPYDER

百般思念 提交于 2019-12-11 06:45:07

问题


This is PyQT code that I have to be executed in Spyder. The first time, I executed it, it works well. On the second time, it says:

QWidget: Must construct a QApplication before a QPaintDevice "

I searched for solution but nothing worked for me.

from PyQt4 import QtGui, QtCore
import sys

class Window(QtGui.QWidget):
    def __init__(self):
           QtGui.QWidget.__init__(self)
           self.button = QtGui.QPushButton('Test', self)
           self.button.clicked.connect(self.handleButton)
           layout = QtGui.QVBoxLayout(self)
           layout.addWidget(self.button)

    def handleButton(self):
           print ('Hello World')

if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
#sys.exit(app.exec_())

I even commented sys.exit() which some people proposed. Could someone help me to get rid of this error as I am restarting the kernel every other time to execute.


回答1:


First, your example is not really minimal. You'll observe, that

from PyQt4 import QtGui

if __name__ == '__main__':
    app = QtGui.QApplication([])
    w = QtGui.QWidget()
    w.show()
    app.exec_()

already does the trick.

My guess is that the console in which you let this script run twice is not deleting the QApplication (type app in the console you see the variable is still there).

In the second run, the newly created QApplication interferes with the still existing from the old run. They all run within the same console and it depends a bit on what spyder does when running a file.

To circumvent this delete the app before another run:

del app


来源:https://stackoverflow.com/questions/42970299/pyqt-exit-error-in-spyder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!