Importing the .ui form

I am new to Python and Py QT5, for the tutorial on the following page : Build GUI layouts with Qt Designer for PyQt5 apps, how do I import the form UI file in Python and interact with the Text labels? Previously there was only a tutorial on importing the MainWindow UI.


I am also new to Python so there may be more elegant solutions. In the sample below created a class called MyWindow that inherits from QWidget instead of QMainWindow. If you made a dialog ui file use QDialog.

from PyQt5 import QtWidgets, uic
import sys, os

class MyWindow(QtWidgets.QWidget):

    def __init__(self, *args, **kwargs):
        super(MyWindow, self).__init__(*args, **kwargs)

        # Load the UI Page - added path too
        ui_path = os.path.dirname(os.path.abspath(__file__))
        uic.loadUi(os.path.join(ui_path, "chanlCfg.ui"), self)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    main = MyWindow()
1 Like

Hi @Albert_Ang welcome to the forum!

It’s a great question – I plan to add a more in-depth example of this in the tutorial. But the simple answer is that you can import any UI type in Python in much the same way (as @tcarson4344 showed is right). How you interact with the form elements though depends on how you name them in Qt Designer.

In Qt Designer click on any of the widgets you work with, then in the panel find the “objectName” parameter. This is the name that that widget will be known by in Python.


So, for example, if you enter input_name as an objectName then that widget will be available in Python under self.input_name.

1 Like

Thank your very much for providing the example code!

Hi Martin, thank you very much for answering my question.

1 Like

To convert the ui to a python script you can open a command prompt in same folder as the .ui file and type

pyui5 -x file.ui -o

then edit the

One thing to watch when generating a .py file in this way from a UI file and editing it @covaj318218817
is that if you make any changes to the UI in Designer and recompile it, it would overwrite the file.

Instead can compile the UI file without the -x flag to create a non-executable compiled Python file & then import that into a and use it there. Then you can regenerate the compiled file any time, without overwriting changes you make in

e.g. (your compiled widget, named MyWidget in

import sys
from PyQt5 import QtWidgets
from mywidget import MyWidget

app = QtWidgets.QApplication(sys.argv)
window = MyWidget()
window .show()