0

I want to improve my code but currently have not much idea how. So I used Qt Designer and created a main window plus 3 dialogs which can be opened from main window. Converted .ui files to .py files and created the MainWindow class which manages all. Everything works fine, but for me this looks wrong:

class MainWindow(QMainWindow, Ui_MainWindow):
    # init and else
    [...]

    def open_add_dialog(self):
        self.dialog = AddDialog()
        self.dialog.show()

    def open_edit_dialog(self):
        self.dialog = EditDialog()
        self.dialog.show()

    def open_about_dialog(self):
        self.dialog = AboutDialog()
        self.dialog.show()

    def assign_widgets(self):
       self.actionAdd.triggered.connect(self.open_add_dialog)
       self.actionEdit.triggered.connect(self.open_edit_dialog)
       self.actionAbout.triggered.connect(self.open_about_dialog)

Code is simplified.. So as you see I've 3 almost equal methods. So the question comes to my mind is it possible to merge all into one? What I want is something like this:

def open_dialog(self):
    sender = self.sender()
    sender.show()

1 Answers1

1

I think you should never use the sender method of Qt because it makes calling the method from another function impossible, you can then only use it via the signal/slot mechanism. It therefore says in the documentation that: "This function violates the object-oriented principle of modularity". Using it during debugging is fine, of course.

In your case the methods are quite small. You could use lambdas in the connect statement so that you don't have to make separate methods. Or you could create the dialogs in the constructor and only connect to the show methods. Like this:

class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self):
        self.add_dialog = AddDialog()
        self.edit_dialog = EditDialog()
        self.about_dialog = AboutDialog()

    def assign_widgets(self):
       self.actionAdd.triggered.connect(self.add_dialog.show)
       self.actionEdit.triggered.connect(self.edit_dialog.show)
       self.actionAbout.triggered.connect(self.about_dialog.show)
titusjan
  • 5,376
  • 2
  • 24
  • 43