'How to add functionality to widgets (PyQt5 ) in separate .py
I'm struggling to understand the general structure of how to work with PyQt. I want to have my main file
class MainWindow(qtw.QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__ == '__main__':
app = qtw.QApplication([])
widget = MainWindow()
widget.show()
app.exec_()
separate from the ui-file
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.LeftSide = QtWidgets.QWidget(self.centralwidget)
self.LeftSide.setObjectName("LeftSide")
self.verticalLayout = QtWidgets.QVBoxLayout(self.LeftSide)
self.excel.setObjectName("something")
self.verticalLayout.addWidget(self.something)
...
as I want to be able to change the ui later on but retain all functionality. The UI has widgets within widgets.
How do I access these widgets in the separate main.py file or in separate files and add functionality, preferably by creating a class for each widget?
Thanks a lot for any help!
Solution 1:[1]
Basically you don't even have to convert .ui file to .py. You can load it to your window with:
from PyQt5 import uic
class MainWindow(qtw.QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
uic.loadUi("path/filename.ui",self)
self.setUI()
Then you can access your widgets from ui like:
self.centralWidget
For adding different functionalities to objects from ui file there are several options:
- Monkey patching (not really recommended but ok for small changes).
- Promoting a widget using QtCreator or QtDesigner. Basically you create a subclass of let's say QWidget in your MyWidget.py file, name that class MyWidget and add all needed functionalities. Then you place QWidget on your form in either QtCreator or QtDesigner click with RMB on it and click Promote to ... . Then you specify path to your MyWidget.py file in field Header file and class name to Promoted class name. This will replace standard widget with your custom when loading ui file. Useful link: https://www.mail-archive.com/[email protected]/msg17893.html.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bartek |