PyQt5.QtWidgets 模块的最佳导入实践

3
我曾使用PyQt5编写了许多代码,使用了其强大的布局和窗口小部件。 但是,我不知道如何正确导入我所需的大量模块,虽然一切都能正常工作,但我想了解在使用PyQt5时的最佳实践。 我读到说并没有确切的方法,但我欢迎任何建议。 我已经阅读了这里的所有内容:https://peps.python.org/pep-0008/,但仍然难以为PyQt5找到一个好的解决方案。

到目前为止,我的做法如下:

from PyQt5.QtWidgets import QApplication, QMainWindow, QStatusBar, QTextEdit, QFileDialog
from PyQt5.QtWidgets import QLabel, QWidget, QHBoxLayout, QPushButton, QLineEdit
from PyQt5.QtWidgets import QRadioButton, QGridLayout, QFormLayout, QAction
from PyQt5.QtCore import Qt
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui

这相当繁琐。 我也知道不应该使用

from PyQt5.QtWidgets import *

那么什么是最简洁的方法?


1
请注意,您的问题有点基于个人观点,并且要求“最佳实践”通常被认为是SO上的离题问题。无论如何,请考虑到虽然不鼓励使用通配符导入,但它们并非“禁止”。如果您的项目很大,迟早会导入许多类,而且由于“实际”加载在C++库中(由几个“单片”库组成),因此该导入很少对启动产生不同的影响。也就是说,记住您还可以使用from PyQt5 import QtWidgets,然后在代码中使用QtWidgets.ClassXYZ - musicamante
2个回答

2

我通常做的事情,也是从其他发布的代码中借鉴来的,是将内容分组放在括号内:

from PyQt5.QtWidgets import (QApplication, QMainWindow, QStatusBar, QTextEdit, QFileDialog,
                             QLabel, QWidget, QHBoxLayout, QPushButton, QLineEdit,
                             QRadioButton, QGridLayout, QFormLayout, QAction)
from PyQt5.QtCore import Qt
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui

太棒了,我不知道这个,现在代码开头更加整洁了。谢谢! - crazydecibel

1
您可以将使用的函数和类包装成自定义小部件或纯py文件,然后在主框架类中只导入这些自定义小部件。
例如,如果您有一个实现自定义小部件类的customwidgetscript.py文件,它可能如下所示:
from customwidgetscript import customwidget

在与mainframe.py相同的文件夹中的customwidgetscript.py中,您可以像这样导入内容:
from PyQt5.QtWidgets import QLabel, QWidget, QHBoxLayout, QPushButton, QLineEdit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接