Martin
Martin

Reputation: 11

Python: QT5 include ui.py in main python script

this might be an basic question, but I didn't found a working solution yet:

This is my first Python UI Script... I have the idea of putting the UI in one file without any functionality and putting all the actual code and algorithms into another file, but I don't know if this is good practice or not and how to make this work.

I have created an UI with GTDesigner and converted this into MainWindowPy.py by using pyuic5.

This gave me:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        [...]
    def retranslateUi(self, MainWindow):
        [...]

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Now I want to leave this MainWindowPy.py untouched, because the UI can change in the further delevopment.

How can I link and run this file in my MainApplication.py script and how can I access UI-elements like buttons?

I tried wrapping the whole UI-code in a function and then imported this as a module in MainApplication.py and called the function through this module. It worked, but that's not "untouched".

I know about subprocess.Popen(), but maybe there is a better way?

Upvotes: 0

Views: 1530

Answers (1)

Vince W.
Vince W.

Reputation: 3785

The code generated in this case is a mixin class. To use it in a different file you simply import it and create a new class with two base classes, one which is the Qt Class you want it to be and the second which is the mixin class from your uic generated file. In the init of your new class you must run the init method of the primary base class, and the setupUi method of the mixin class:

from MainWindowPy import Ui_MainWindow
from PyQt5 import QtWidgets

class myMainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(myMainWindow, self).__init__(parent)  # call init of QMainWindow, or QWidget or whatever)
        self.setupUi(self)  # call the function that actually does all the stuff you set up in QtDesigner

now to use it, you initiate your custom class that you made

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = myMainWindow()
    MainWindow.show()
    sys.exit(app.exec_())

Upvotes: 2

Related Questions