Home > OS >  Shorter way to make QWidget to a QMainWindow pyqt5
Shorter way to make QWidget to a QMainWindow pyqt5

Time:06-29

I'm testing on how can I improve more developing in pyqt5 UI I'm just curious if there is a shorter way to make a QWidget to a QMainWindow other than this code:

class PayrollMainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(PayrollMainWindow, self).__init__()
        PayrollWidget = self.Payroll()
        self.setWindowTitle("PSA Payroll")
        self.setCentralWidget(PayrollWidget)

        self.menuBar = self.menuBar()
        fileMenu = self.menuBar.addMenu('File')
        editMenu = self.menuBar.addMenu('Edit')
    class Payroll(QtWidgets.QWidgets):...

CodePudding user response:

So your code almost demonstrates the standard way, however I would never suggest defining a widget subclass inside the MainWindow definition block. They should both be declared at the global level like so:

class Payroll(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        ...


class PayrollMainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
         super().__init__(parent=parent)
         payrollWidget = Payroll(parent=self)
         self.setCentralWidget(payrollWidget)
         ...

If your looking for a quicker way and you don't need overwrite any functionality then you could forgo subclassing altogether for example:

mainwindow = QMainWindow()
payrollWidget = QWidget(parent=mainwindow)
mainwindow.setCentralWidget(payrollwidget)
mainwindow.setWindowTitle('PSA Payroll')
menubar = mainwindow.menuBar()
filemenu = menubar.addMenu('File')
editmenu = menubar.addMenu('Edit')
  • Related