Divide the MainWindow class into smalller classes
-
I'm building a GUI app with PySide6 using QtDesigner. The MainWindow class has grown and is hard to manage. How do I divide this MainWindow class?
I can't post my whole app, but the question is too general for it anyway. The header of my MainWindow class is this:class MainWindow(qtw.QMainWindow, Ui_MainWindow): def __init__(self, interfejs_robot): super().__init__() self.setupUi(self)
I'd say standard stuff.
I can see thatself.setupUi(self)
is creating a bunch of attributes for the MainWindow class, and it has to be called inside it, because it requires MainWindow argument. So I thought that I somehow need to get into those attributes through an outside class, but how to do that? Or is there maybe a completely different solution? -
@Adar70
setupUi()
is just for configuring the main window itself. It will access private variables of that class. You would not normally need or want to split this off or move to another module.If the whole class/file is getting large then look at where it has much code of your own and think about factoring/splitting that off, rather than the internals of
setupUi()
. -
@Adar70 said in Divide the MainWindow class into smalller classes:
But now how do I access them if they're in the MainWindow class?
From where do you want to access them? These buttons are part of the class you create and should be accessed only inside this class, else you're creating tight coupling between different classes, which is bad design.
"So I thought that I somehow need to get into those attributes through an outside class, but how to do that?" - what do you mean by that? Other classes should not know anything about these attributes which are implementation detail. What problem are you trying to solve?
-
@Adar70 said in Divide the MainWindow class into smalller classes:
So how do I overcome the problem of a big MainWindow class?
You can create dedicated UI widget classes which you then instanciate in yor main window. Each of these widget classes implements part of the UI and also handles its logic.
See https://doc.qt.io/qt-6/designer-using-custom-widgets.html -
@Adar70
We don't really know because we don't know what the 30 methods do.BTW "30" methods is not a huge number for a (main window) class.
If lots of these methods are to do with, say, the tree widget you mention you could consider putting them all in their own class. @jsulm mentions "custom widgets". In that link the Promotion is the simplest way to replace a plain
QTreeWidget
with your class derived from that, which could hold a variety of methods operating on it. The User Defined custom widgets require more work and are only required if you need specialized visuals in Designer, which you probably do not.