Home > Software engineering >  Why do most PyQt tutorials create classes from widgets?
Why do most PyQt tutorials create classes from widgets?

Time:09-14

TLDR why do people create classes (Window for example) when its only going to be used once?

Some examples:
RealPython, the first code block
PythonBasics, first code block
PythonPyQt, first code block

Why can't they put the code in the main program (using the RealPython example):

if __name__ == "__main__":
    window = Qwidget.setWindowTitle("QHBoxLayout Example")
    window.show()
    # Create a QHBoxLayout instance
    layout = QHBoxLayout()
    # Add widgets to the layout
    layout.addWidget(QPushButton("Left-Most"))
    layout.addWidget(QPushButton("Center"), 1)
    layout.addWidget(QPushButton("Right-Most"), 2)
    # Set the layout on the application's window
    window.setLayout(layout)
    print(window.children())
    sys.exit(app._exec())

Instead of

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QHBoxLayout Example")
        # Create a QHBoxLayout instance
        layout = QHBoxLayout()
        # Add widgets to the layout
        layout.addWidget(QPushButton("Left-Most"))
        layout.addWidget(QPushButton("Center"), 1)
        layout.addWidget(QPushButton("Right-Most"), 2)
        # Set the layout on the application's window
        self.setLayout(layout)
        print(self.children())

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

CodePudding user response:

if you have a big program it's really hard to put all of them in the main program and deal with all the widgets created in a single file.

with separate classes you have access to the QWidget, and you can also inherit additionally some QDesigner created GUIs.

from Codebase.GUI.MyMainWindow import Ui_MainWindow

class ExampleDesignerMainWindow(QMainWindow, Ui_MainWindow)
    def __init__(self)
        super(ExampleDesignerMainWindow, self).__init__()
        self.setupUi(self)
        # do something

and then you can have access to everything and instantiate in the "main program" whenever you want.

  • Related