Pyqt5 Buttons Not Connecting
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 connect to
Solution 1:
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:
defmain():
"""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 theCtrl
instance, while the argument should be theUI
instance instead (which will result in a crash, as Qt will get an unexpected argument type); you can useself._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)
Post a Comment for "Pyqt5 Buttons Not Connecting"