PyQT5 Application Load and Display UI Designed by Qt Designer – PyQT5 Tutorial

By | April 19, 2021

We often use qt designer to design a UI for a qt application. However, how to use this ui in your qt5 application? In this tutorial, we will introduce you how to do.

Design UI using qt designer

It is very easy to create a ui using qt designer, here is an example:

qt designer example

You can create a window by clicking and dragging widgets.

Convert ui file to python script file

In order to use ui created by qt designer, we should convert ui files generated by qt designer to python script files. Here is a tutorial:

Convert Qt Desiger UI File to Python Script File (.py) – PyQT Tutorial

Then, we can use these ui python script files in your pyqt5 application.

How to load and display ui created by qt designer in pyqt5 application?

Firstly, we should add ui python script files in our python project. Then, we can use them.

Here is an example:

# -*- coding: utf-8 -*-
import sys
import os
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog
from main_home import *

if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    # create a main window 
    main = QMainWindow() 
    main.setFixedSize(500, 320)
      
    main_win = Ui_PDFPageSpliter() 
    main_win.setupUi(main)
   
    main.show()
    sys.exit(app.exec_())

In this example, Ui_PDFPageSpliter is a ui designed by qt designer. In order to display it in our application, we should set up a main window for it. Here is the core code:

    main_win = Ui_PDFPageSpliter() 
    main_win.setupUi(main)

Then we will display it as follows:

main.show()

We also can use main_win to access ui elements in Ui_PDFPageSpliter. For exmaple:

In order to bind a click event for a button in Ui_PDFPageSpliter, we can do as follows:

main_win.btn_open_help_win.clicked.connect(lambda: open_help_win(main_win))

More about button click event, you can read:

An Introduce to PyQT Button Bind Click Event with Examples – PyQT Tutorial

Leave a Reply