PyQt5 buttons not connecting

后端 未结 1 1065
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-27 11:46

I am trying to build a simple GUI using PyQT5, with 3 buttons to open file browsers and one more to run processing with the selected files, but I can\'t get my buttons to connec

相关标签:
1条回答
  • 2021-01-27 12:43

    The problem is that you are not keeping any persistent reference to the Ctrl() instance you are creating. This results in python garbage collecting it as soon as the instance is created.

    To solve the issue, just assign it to a variable:

    def main():
        """Main function."""
        # Create an instance of `QApplication`
        app = QApplication(sys.argv)
        # Show the app's GUI
        view = UI()
        view.show()
        setup = {}
        # Create instance of the controller
        ctrl = Ctrl(setup=setup, view=view)
        # Execute app's main loop
        sys.exit(app.exec_())
    

    Some considerations:

    • while separating logic from interface is usually good practice, it's a concept that needs to be used with care, as sometimes it only makes things more complex than they should be. Most of the times (especially with simple programs), it only makes a bigger codebase without giving any actual benefit: it's harder to read and to debug, and you'll probably end up continuously switching from the logic parts and the ui parts of your code;
    • your code shows one of the drawback of that concept: when you create the file dialog, you're using self, but in that case it refers to the Ctrl instance, while the argument should be the UI instance instead (which will result in a crash, as Qt will get an unexpected argument type); you can use self._view instead, but, as said, the whole separation in this case just makes things unnecessarily complex;
    • using strings for dictionary keys that refer to internal objects is rarely a good idea (especially when using long descriptive strings like you did);
    • when importing more than one element from a module, it's usually better to group them instead of using single line imports: it makes the code tidier and easier to read and inspect: from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QFileDialog)
    0 讨论(0)
提交回复
热议问题