Qt for Python UiFiles

From Qt Wiki
Jump to: navigation, search


This page describes the use of Qt Creator to create Graphical Interfaces for your PySide Software. You will need Qt Creator to design and modify your interface (ui file)

If you don't know how to use Qt Creator, please go to Using Qt Designer.

At Qt Creator, create a new Qt Design Form, choose "Main Window" for template. And save as "mainwindow.ui". Add a Qlabel to the center of the centralwidget.

Your file (mainwindow.ui) should look something like this:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
 <property name="geometry">
 <rect>
 <x>0</x>
 <y>0</y>
 <width>82</width>
 <height>64</height>
 </rect>
 </property>
 <property name="windowTitle">
 <string>MainWindow</string>
 </property>
 <widget class="QWidget" name="centralwidget">
 <layout class="QGridLayout" name="gridLayout">
 <item row="0" column="0">
 <widget class="QLabel" name="label">
 <property name="text">
 <string>Hello World!</string>
 </property>
 </widget>
 </item>
 </layout>
 </widget>
 <widget class="QMenuBar" name="menubar">
 <property name="geometry">
 <rect>
 <x>0</x>
 <y>0</y>
 <width>82</width>
 <height>21</height>
 </rect>
 </property>
 </widget>
 <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

Now, using PySide2 we will load the ui file and start our application:

 1 # main.py
 2 import sys
 3 from PySide2.QtUiTools import QUiLoader
 4 from PySide2.QtWidgets import QApplication
 5 from PySide2.QtCore import QFile
 6 
 7 if __name__ == "__main__":
 8     app = QApplication(sys.argv)
 9 
10     file = QFile("mainwindow.ui")
11     file.open(QFile.ReadOnly)
12 
13     loader = QUiLoader()
14     window = loader.load(file)
15     window.show()
16 
17     sys.exit(app.exec_())
And to run it, just a
python main.py
will do the job.