Best practice to import PyQt5.QtWidgets modules

Viewed 128

I have written many codes using PyQt5 and all its powerful layouts and widgets. But somehow I am missing how to properly import the great amount of modules that I need for my codes. Everything works fine, I just want to understand the best practice when working with PyQt5. I read that there is not an exact way, but any suggestion is appreciated. I read all about here: https://peps.python.org/pep-0008/ but still I find difficult to find a good solution for PyQt5.

What I do up to now is as follows:

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

which is quite cumbersome. I know also that I should not use

from PyQt5.QtWidgets import *

so what is the most neat way?

2 Answers

What I usually do and I've borrowed it from other code posted here is to group things in parentheses:

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

You could wrap the used functions and classes into custom widgets or plain py-files and in your main frame class only import those custom widgets.

For example if you have a customwidgetscript.py that implements a customwidget class it would look something like:

from customwidgetscript import customwidget

In that customwidgetscript.py in the same folder as your mainframe.py you could have your imports like this:

from PyQt5.QtWidgets import QLabel, QWidget, QHBoxLayout, QPushButton, QLineEdit
Related