Python 来自 QWidget 的“必须在 QPaintDevice 之前构造 QApplication”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19383684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:37:11  来源:igfitidea点击:

"Must construct a QApplication before a QPaintDevice" from QWidget

pythonqtpyqt

提问by bricky149

I'm busy porting an IRC client from Python 2.6 to 3.3 and I've stumbled across a problem with PyQt. The application originally used PyQt4, I'm also recoding it to get it to work with PyQt5 but I'm getting an error without any line references: "QWidget: Must construct a QApplication before a QPaintDevice". I have narrowed the issue down to a single class.

我正忙于将 IRC 客户端从 Python 2.6 移植到 3.3,并且偶然发现了 PyQt 的一个问题。该应用程序最初使用 PyQt4,我也在重新编码它以使其与 PyQt5 一起使用,但我收到一个没有任何行引用的错误:“QWidget:必须在 QPaintDevice 之前构造一个 QApplication”。我已将问题缩小到一个类。

I understand it's been asked here many times already but I couldn't extract a sure-fire answer for my case so I apologise if my question appears ignorant.

我知道这里已经被问过很多次了,但我无法为我的案例提取一个确定的答案,所以如果我的问题显得无知,我深表歉意。

Here's some of the code: http://pastebin.com/Lj60icgQ

这是一些代码:http: //pastebin.com/Lj60icgQ

Stupid me didn't put the "app" variable just after the import statements when I should've. I then put the rest of the code at the bottom of the main file and I'm not longer getting that error. Thanks for the help!

愚蠢的我没有在应该的时候把“app”变量放在导入语句之后。然后我把其余的代码放在主文件的底部,我不会再收到那个错误了。谢谢您的帮助!

采纳答案by AlexVhr

I'm afraid single file will not be enough in this situation - the execution flow is not clear just from this one module. The message in question usually appears when you try to use some resources/create some objects that require initialized QApplication - like QIcon, for example.

恐怕在这种情况下单个文件是不够的 - 仅从这个模块中执行流程并不清楚。当您尝试使用一些资源/创建一些需要初始化 QApplication 的对象时,通常会出现有问题的消息 - 例如 QIcon。

Instantiation of Qt-based GUI application usually looks like this:

基于 Qt 的 GUI 应用程序的实例化通常如下所示:

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    main_window = MainWindowClass()
    main_window.show()
    sys.exit(app.exec_())

回答by Vicent

The error message is pretty clear: you are trying to draw a QWidget(which in PyQt4.5inherits QPaintDeviceand QObject) before you instantiate the QApplication. But your code is too large for reading it line by line. Try to isolate the error building a small application and adding functionality step by step. Or use a debugger (IDEs like Eclipse+ PyDevare supposed to be able to debug your app). Or provide us with a small, self contained example of the problem.

该错误信息是很清楚的:你正在尝试绘制QWidget(在PyQt4.5继承QPaintDeviceQObject实例化)前QApplication。但是您的代码太大,无法逐行阅读。尝试隔离构建小型应用程序和逐步添加功能的错误。或者使用调试器(像Eclipse+PyDev这样的IDE应该能够调试你的应用程序)。或者为我们提供一个小的、自包含的问题示例。