Pyside + Qt Designer更好的编码

时间:2016-07-01 22:48:08

标签: python pycharm pyside qt-designer

我想改进我的代码,但目前还没有多少想法。 所以我使用了 Qt Designer 并创建了一个主窗口和3个可以从主窗口打开的对话框。将.ui文件转换为.py文件并创建管理所有文件的MainWindow类。 一切正常,但对我来说这看起来不对:

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)

代码被简化..所以当你看到我有3个几乎相同的方法。所以我想到的问题是可以将所有合并为一个吗?我想要的是这样的:

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

1 个答案:

答案 0 :(得分:1)

我认为你永远不应该使用Qt的sender方法,因为它使得从另一个函数调用方法变得不可能,你只能通过信号/插槽机制使用它。因此它在the documentation中说:“这个函数违反了面向对象的模块化原则”。当然,在调试期间使用它很好。

在您的情况下,方法非常小。您可以在connect语句中使用lambdas,这样您就不必使用单独的方法。或者您可以在构造函数中创建对话框,并仅连接到show方法。像这样:

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)