Перейти к содержимому

Как преобразовать ui в py pyqt5

  • автор:

Python GUI’s with PyQt

This tutorial covers the basics of how to create GUI’s in Python using PyQt5. I will demonstrate how to find the designer and basic usage, converting .ui to .py, running the output file and connecting events to methods.

Important First Note

Please understand this process is not the recommended method when using PyQt5 designed / pyuic; this is simply a demonstration of designing a UI using the PyQt5 designer tool, generating Python code and then partially understanding what comes out.

This tutorial is not obsolete however as it can help you get a basic grasp of how to use PyQt5.

The reason the method demonstrated below is not recommended is due to the fact if you use pyuic again to turn a .ui file into a .py file, it will overwrite all your changes to the file. I have a tutorial at How to Import a PyQt5 .ui File in a Python GUI which better explains how you should import the generated script so your changes will not be overwritten.

If you only intend on using the generated code as an initial layout and not re-generate the code (I do this a lot), you may find this method easier than importing as you can make changes to the layout a lot easier this way.

Setting up the Environment

For this tutorial, you will need a version of Python equal to or above 3.5. I do however recommend to get a more recent version than 3.5 as I had issues with 3.5.2; a simple upgrade to 3.6.6 fixed this. If you don’t know where to get Python, look here.

Now you will want to install pyqt5 and pyqt5-tools. To do this, we can use pip. Call the two commands python -m pip install pyqt5 and python -m pip install pyqt5-tools . After each command completes, make sure to verify that they installed properly by checking if it says they were installed successfully.

You should now be able to execute the following in Python with no errors:

If you have issues installing PyQt5 for some reason, you could try the installers at its sourceforge page.

Using the Designer

When you ran the pip install pyqt5-tools command, this installed tools that we can use to help with building GUIs.

First, we need to locate where they are now, to do this we can run the following code in Python:

This will print out a couple of paths, for me it prints: [‘C:\\Python36’, ‘C:\\Python36\\lib\\site-packages’] . Here we can see my Python distribution location and the site-packages folder. Open up a file explorer and navigate to the site-packages folder. In this folder, you then want to locate the pyqt5-tools folder and open it. In this folder, you should find a few files, one named designer.exe.

After recent updates to pyqt5-tools , designer.exe has been moved to the ‘Scripts’ folder in your Python distribution. To find this using the paths we found before, go to the first path returned (‘C:\Python36’ in my case) and then go into the ‘Scripts’ folder; you should find designer.exe in here.

Using the Designer

designer.exe is the program that we will use to make designing GUIs a lot easier; remember the location of this or create a shortcut to it and then run it (double click if you wish). You will be welcomed with a selection window; select «Main Window» and then click «Create».

Initial Display

You will now be shown an empty window in the middle of the designer’s window with widget options on the left and some other windows to the right.

On the left, you can drag widgets from the drop-downs onto the MainWindow object in the centre. On the right, in the Object Inspector, you can see the current widgets in your window. Right below that is the Property Editor that allows you to modify the widget currently selected.

Window Labeled

Creating a Simple Window

For this example, we will be just putting a button that prints «Hello World!» when pressed in the Window; soon we will work with a larger example when the basics are out of the way.

First, make your window a bit smaller by clicking and dragging the bottom right of the window (or any part on the edge) to change the size as you would do on any other window. Now find the «Push Button» widget under the Buttons section (on the left) and drag it into the window anywhere. You can double click on the button now to rename the text in it; set it to «Print Message».

You may now want to change the size of the button, to do this click on the button until there are blue squares on each of its corners and edges. Use these blue squares to re-size the button to a size you want.

When you are happy with what you have done (this is just a simple practice) then click File -> Save in the top left and save it somewhere where you will remember; I will save it as ‘printMessage.ui’ on my desktop.

Converting .ui to .py

Now that we have our .ui file, we can convert it into Python code so we can modify and run it.

To do this we need to locate pyuic5. pyuic5 converts .ui to .py in one simple command and is located in the ‘Scripts’ folder in your Python distribution. If you don’t know where this is, execute the following:

You will be provided with a path of where your python distribution is located; mine is at C:\Python36 (we saw this before when looking for the designer). Now go to this directory and open the ‘Scripts’ folder in there.

In this folder you will see a few executables to make Python in the terminal easier, you should also be able to see a file named pyuic5.exe ; this is what we are going to use. Open cmd and then use the cd command to get to the directory; for example, I will execute cd C:\Python36\Scripts in cmd. Now if you type pyuic5 you should be provided with a small error message saying «Error: one input ui-file must be specified»; this is good, we are in the right place.

To convert we now need to pass in the .ui file we created before and decide on an output filename and location. My .ui file is on my desktop currently so I will put the created .py file on the desktop also to make it easier. Now we can convert using pyuic5 -x <.ui file> -o <output.py file> , for example I will use pyuic5 -x «C:\Users\Brent\Desktop\printMessage.ui» -o «C:\Users\Brent\Desktop\printMessage1.py» . This should take not very long at all and show no errors; the python script you declared after -o will now exist — for me, a file called printMessage1.py is now on my desktop.

Running the Output and Hooking up the Button

Now that you have the .py file containing the ui code, open it in IDLE or whatever IDE you use. Your code should look something like this:

Start GUI Code

Run the code and then wait for the GUI to appear; it currently won’t do anything when you press the button so we will set that up.

Go back into the code for this GUI and look in the setupUi definition. You should see a class variable called self.pushButton which later has its text set to «Print Message» in the retranslateUi definition below. This is the object of our button that we need to make do something.

First, we need to create our method, this method can be in the global scope or in the class scope, for simplicity I will put it in the class scope. After the retranslateUi definition, create a new class called printMessage that takes self as an argument since it is part of the class now. Inside this put what you want the script do to when you press the button, for this example, I will print «Hello World!».

Now that you have created the method to run, we can attach it to the button. Using the button variable we found before, we can call .clicked.connect() on it passing in the name of our method we just created (make sure to remember self. for class variables). Put this line at the bottom of the setupUi definition so it will be executed when the GUI is built.

Remember to not include () when passing the method here or it will not work.

Your script should now look something like this, don’t worry if it is a bit different.

Start GUI Code

Run the code again and now when you press the button you should see that the script runs the code that you defined in the method you attached to the button.

More Advanced Example

In this next example, I will show you how to put images in the GUI, add a selection dialog box and add data to a table.

Open the designer back up and create a new MainWindow. Now create and position the 5 widgets described below: — Label (in Display Widgets): This label will be the widget we use to show the image — PushButton (in Buttons): This button will allow us to select the image to show in the Label — ListWidget (in Item Widgets): This will hold and display entries we add to it — LineEdit (in Input Widgets): This will allow us to enter what we want into the table — PushButton (in Buttons): This will add the item in the LineEdit to the table

MainWindow advanced layout before editing properties

If you click on a widget, for example, the button that will be selecting the button, the Property Editor on the right will display all the options for that object. In there you can edit things like the exact size/position, borders (frames), tooltips and fonts.

First, we will want to edit the Label that is holding the image; click on the label to open it up in the Property Editor. Find «text» under the QLabel section and delete the text, this is the same as double-clicking and removing the text. Now go to the QFrame heading and change «frameShape» to box, this will but a border around the image.

Image Label Properties

Now click on the select image button and in the QWidget header go to «font». This has many options inside of this so play around to get a font you like (you can leave it if you want). Your GUI should now look something like this:

MainWindow advanced layout before editing properties

To help you later on, you can also change the «objectName» under QObject in the Property Editor for all widgets so you can identify them easier later. Here is what I named mine: — Select Image Button: selectImageBtn — Image Label: imageLbl — LineEdit: lineEdit — Add button: addBtn — ListWidget: listWidget

Like we did before, convert this .ui file (after saving it) to a .py file.

Connecting Events to Methods

Now we need to connect all the actions together. The select image button will need to be connected to a method that displays an image selection dialog which will then put an image in the label. Also, we will need to make the ‘add’ button add the text in the lineEdit object into the listWidget object.

Your converted .py code should currently look something like this: Code download: MainWindowAdvanced1.py

If you open your .py file in IDLE, you can see that the names we gave each widget have passed through to the names of the actual objects. I also recommend running the code now to make sure it works.

Object names in code

Linking the Image Button

First, you will want to create a class definition called setImage ; make sure this takes self as it is a class definition. In this method, we want to ask the user for an image (not just any file). If they provide a file, we then need to create a pixmap object and then set the pixmap object to the image label. Before we set it, it is ideal to scale the image to fit inside the label without stretching and aligning it to the centre. Your method will look like this:

In the QtWidgets.QFileDialog.getOpenFileName method call, you can see I have passed the string «Image Files (*.png *.jpg *jpeg *.bmp)» . This declares the type of files I will accept. If you want to accept any file, remove this string completely. If you want to make it so the user could switch it to all files themselves, set it to «Image Files (*.png *.jpg *jpeg *.bmp);;All Files (*)» ; play around with this to get the idea of what is going on, you can add more file extensions and selections if wanted.

Now we need to attach the button to the definition. This can simply be done using the connect method we used previously; make sure to put it at the bottom of the setupUi definition as we did before:

Run the script and make sure that your button works. Initially, the label will be clear but each time you select a file it should change to the selected file.

Linking the Add to List Button

We will now need to create another class definition called addItem like before. In this method, we need to get the value of the lineEdit object and then clear it. We can then simply add the value we just got to the listWidget. After you have done that, the method should look like this:

And then like before, we need to connect the button to the method just under the last one we did:

Running the script now you should be able to type in the text edit item and then press add for the item to go into the list.

Owner of PyTutorials and creator of auto-py-to-exe. I enjoy making quick tutorials for people new to particular topics in Python and tools that help fix small things.

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

Qt designer is a powerful tool to design pyqt gui. It will create some ui files.

ui files created by qt designer

However, in order to use these ui files in python, we should convert them to .py files. In this tutorial, we will introduce you how to convert.

First of all, you should install Qt Designer.

Then, we can use pyuic5 command to convert. Here is an example:

In this example, designer.ui is the input ui file, designer.py is the output python script file.

However, if you encounter Error: one input ui-file must be specified . You can fix this error by this tutorial:

Python GUI framework PyQt5

There is not really much software that uses Python to develop graphical interfaces. Compared to GUI interfaces, probably Web way applications are more popular. But for other programming languages like me you such as C# or WPF may not be a good tool.

Common GUI frameworks

    : Qt is a cross-platform C++ GUI library. QT was once owned by Nokia and then sold to Digia, a Finnish software company. Oyj. PyQt5 is a Python interface based on Digia’s Qt5, and consists of a set of Python modules. It runs on multiple platforms, including Unix, Windows, and Mac OS. : Pyside is the official Python package provided by QT, the last version is Pyside2, corresponding to QT5, the latest version of the naming rules have been adjusted, changed to Pyside6, corresponding to QT6 version. As the official production is more promising, the disadvantage is that the release is late and there is not as much information on the Internet as PyQt5. : Python built-in GUI framework , using TCL implementation , Python embedded in the TCL interpreter , use it without installing additional extension packages , direct import , cross-platform . The downside is that the UI layout all by code, only 15 common components, the display effect is simple. : PySimpleGUI is a layer wrapper of Tkinter. Implementing a custom GUI using PySimpleGUI requires much less code than writing the same GUI directly using Tkinter. : wxPython is a Python language binding to the popular wxWidgets cross-platform GUI tool library. Used more widely, cross-platform, written in C++, with little documentation, users may then need to make some adjustments to the GUI code in different platforms according to the programming content. Problems are not easy to solve, code layout control, not intuitive. : based on wxPython , a package made to overcome the problems of wxPython. : mainly for multi-touch programs, smartphones tablets, etc., also on systems without touch screen functionality, full platform support (Windows, Linux, Mac OS X, Android and iOS.) written in Python and cython, Chinese support Poor Chinese support, you need to download the Chinese library and make your own path. : Write once. Deploy everywhere. : a GUI toolkit for developing native apps using Python. Toga consists of a library of base components with shared interfaces to simplify platform-independent GUI development. toga is available for Mac OS, Windows, Linux ( GTK) as well as mobile platforms such as Android and iOS. : A lightweight Python library for making simple offline HTML/JS GUI applications similar to (but lighter than) Electron, with full access to Python functions (capabilities) and libraries. Full access to Python features and libraries. : a pure Python toolkit for creating GUI applications. It uses Web technologies for rendering the interface. You can use Flexx to create desktop applications, as well as export an application to a standalone HTML document. Because it is developed in pure Python, Flexx is cross-platform. All you need is Python and a browser to run it. is a lightweight cross-platform wrapper (wrapper) around the webview component that allows HTML content to be displayed in its own native GUI window. It allows you to use Web technologies in your desktop applications while hiding the fact that the GUI was built using a browser to the greatest extent possible. : A Python framework that allows you to implement high-quality GUI interfaces with minimal effort, and a unique programming language. enaml combines a declarative language with a constraint-based layout system, making it easy for users to define flexible enaml applications can run on any platform that supports Python and Qt.

Personal thoughts: too much to learn, first learn PyQt5, the reason is that there is more information, learn the rest of friends and then learn pyside6, and finally look at PySimpleGUI, to see if you can solve some simple problems.

PyQt5 Introduction

PyQt is a Python language implementation of the Qt framework, developed by Riverbank Computing, one of the most powerful GUI libraries.PyQt provides a collection of well-designed window controls, each PyQt control corresponds to a Qt control, so PyQt’s API interface is close to Qt’s API interface, but PyQt no longer uses the QMake system and Q_OBJECT macros.

PyQt5 is available in GPL and commercial versions. Free developers can use the free GPL license, and if they need to use PyQt for commercial applications, they must purchase a commercial license.

PyQt5 features are as follows.

  • High-performance Qt-based GUI control set.
  • Ability to run cross-platform on Linux, Window and Mac OS systems.
  • Uses a signal slot mechanism for communication.
  • Full encapsulation of Qt libraries.
  • Can use a full-fledged IDE for interface design and automatic generation of executable Python code.
  • Provides a full range of window controls.

PyQt5 is composed of a series of Python modules with over 620 classes and 6000 functions and methods, the main modules are as follows.

  • QtCore: contains the core non-GUI functions. It is mainly used with time, files and folders, various data, streams, URLs, mime class files, processes and threads.
  • QtGui: Contains the windowing system, event handling, 2D graphics, basic drawing, fonts and text classes.
  • QtWidgets: Contains a set of UI elements for creating desktop applications.
  • QtMultimedia: Contains classes for handling multimedia content and calling the camera API.
  • QtBluetooth: Contains classes for finding and connecting to Bluetooth.
  • QtNetwork: Contains classes for network programming. These tools make TCP/IP and UDP development easier and more reliable.
  • QtPositioning: Contains classes for positioning, using satellites, WiFi and even text.
  • Enginio: Contains classes for accessing and managing the Qt Cloud through the client.
  • QtWebSockets: Contains classes for the WebSocket protocol.
  • QtWebKit: Contains a WebKit2-based web browser.
  • QtWebKitWidgets: Contains classes for the QtWidgets-based WebKit1.
  • QtXml: Contains classes for handling xml, providing tools for SAX and DOM APIs.
  • QtSvg: Provides classes for displaying the content of SVG, Scalable Vector Graphics (SVG), a graphics format that is based on Extensible Markup Language (XML) and is used to describe two-dimensional vector graphics (this quote is from Wikipedia).
  • QtSql: Provides tools for working with databases.
  • QtTest: Provides tools for testing PyQt5 applications.

Installation of PyQt5

Since I want to use fbs for packaging later, fbs may have compatibility problems for Python 3.7 and later, so I chose Python 3.6.8 to build the whole environment. The main content is: Python + PyCharm + PyQt5

Install PyQt5

where pyqt5-tools is a drag-and-drop interface design tool for Qt Designer. The following errors may be reported during installation.

First steps with Qt Designer
Use Qt Designer’s drag and drop interface to design your PyQt5 GUI

So far we have been creating apps using Python code. This works great in many cases, but as your applications get larger or interfaces more complicated, it can get a bit cumbersome to define all widgets programmatically. The good news is that Qt comes with a graphical editor — Qt Designer — which contains a drag-and-drop UI editor. Using Qt Designer you can define your UIs visually and then simply hook up the application logic later.

In this tutorial we’ll cover the basics of creating UIs with Qt Designer. The principles, layouts and widgets are identical, so you can apply everything you’ve already learnt. You’ll also need your knowledge of the Python API to hook up your application logic later.

This tutorial requires Qt Creator to be installed — you can download it free from the Qt website. Go to https://www.qt.io/download and download the Qt package. You can opt to install only Creator during the installation.

Open up Qt Creator and you will be presented with the main window. The designer is available via the tab on the left hand side. However, to activate this you first need to start creating a .ui file.

The Qt Creator interface, with the Design section shown on the left.The Qt Creator interface, with the Design section shown on the left.

To create a .ui file go to File -> New File or Project. In the window that appears select Qt under Files and Classes on the left, then select Qt Designer Form on the right. You’ll notice the icon has «ui» on it, showing the type of file you’re creating.

Create a new Qt .ui file.Create a new Qt .ui file.

In the next step you’ll be asked what type of widget you want to create. If you are starting an application then Main Window is the right choice. However, you can also create .ui files for dialog boxes, forms and custom compound widgets.

Select the type of widget to create, for most applications this will be Main Window.Select the type of widget to create, for most applications this will be Main Window.

Next choose a filename and save folder for your file. Save your .ui file with the same name as the class you’ll be creating, just to make make subsequent commands simpler.

Choose save name and folder your your file.Choose save name and folder your your file.

Finally, you can choose to add the file to your version control system if you’re using one. Feel free to skip this step — it doesn’t affect your UI.

Optionally add the file to your version control, e.g. Git.Optionally add the file to your version control, e.g. Git.

Laying out your Main Window

You’ll be presented with your newly created main window in the UI designer. There isn’t much to see to begin with, just a grey working area representing the window, together with the beginnings of a window menu bar.

The initial view of the created main window.The initial view of the created main window.

You can resize the window by clicking the window and dragging the blue handles on each corner.

The initial view of the created main window.The initial view of the created main window.

The first step in building an application is to add some widgets to your window. In our first applications we learnt that to set the central widget for a QMainWindow we need to use .setCentralWidget() . We also saw that to add multiple widgets with a layout, we need an intermediary QWidget to apply the layout to, rather than adding the layout to the window directly.

Qt Creator takes care of this for you automatically, although it’s not particularly obvious about it.

To add multiple widgets to the main window with a layout, first drag your widgets onto the QMainWindow . Here we’re dragging 3 labels. It doesn’t matter where you drop them.

Main window with 1 labels and 1 button added.Main window with 1 labels and 1 button added.

We’ve created 2 widgets by dragging them onto the window, made them children of that window. We can now apply a layout.

Find the QMainWindow in the right hand panel (it should be right at the top). Underneath you see centralwidget representing the window’s central widget. The icon for the central widget show the current layout applied. Initially it has a red circle-cross through it, showing that there is no layout active.

Right click on the QMainWindow object, and find ‘Layout’ in the resulting dropdown.

Right click on the main window, and choose layout.Right click on the main window, and choose layout.

Next you’ll see a list of layouts which you can apply to the window. Select Lay Out Horizontally and the layout will be applied to the widget.

Select layout to apply to the main window.Select layout to apply to the main window.

The selected layout is applied to the the centralwidget of the QMainWindow and the widgets are added the layout, being laid out depending on the selected layout. Note that in Qt Creator you can actually drag and re-order the widgets within the layout, or select a different layout, as you like. This makes it especially nice to prototyping and trying out things.

Vertical layout applied to widgets on the main window.Vertical layout applied to widgets on the main window.

Using your generated .ui file

We’ve created a very simple UI. The next step is to get this into Python and use it to construct a working application.

First save your .ui file — by default it will save at the location you chosen while creating it, although you can choose another location if you like.

The .ui file is in XML format. To use our UI from Python we have two alternative methods available —

  1. load into into a class using the .loadUI() method
  2. convert it to Python using the pyuic5 tool.

These two approaches are covered below. Personally I prefer to convert the UI to a Python file to keep things similar from a programming & packaging point of view.

Loading the .ui file directly

To load .ui files we can use the uic module included with PyQt5, specifically the uic.loadUI() method. This takes the filename of a UI file and loads it creating a fully-functional PyQt5 object.

A (very) simple UI designed in Qt CreatorA (very) simple UI designed in Qt Creator

As the uid.loadUI() method turns an instance object you cannot attach custom __init__() code. You can however handle this through a custom setup function

To load a UI from the __init__ block of an existing widget (e.g. a QMainWindow ) you can use uic.loadUI(filename, self) for PyQt5.

Converting your .ui file to Python

To generate a Python output file run pyuic5 from the command line, passing the .ui file and the target file for output, with a -o parameter. The following will generate a Python file named MainWindow.py which contains our created UI.

If you’re using PyQt4 the tool is named `pyuic4`, but is otherwise completely identical.

You can open the resulting MainWindow.py file in an editor to take a look, although you should not edit this file. The power of using Qt Creator is being able to edit, tweak and update your application while you develop. Any changes made to this file will be lost when you update it. However, you can override and tweak anything you like when you import and use the file in your applications.

Importing the resulting Python file works as for any other. You can import your class as follows. The pyuic5 tool appends Ui_ to the name of the object defined in Qt Creator, and it is this object you want to import.

To create the main window in your application, create a class as normal but subclassing from both QMainWindow and your imported Ui_MainWindow class. Finally, call self.setupUi(self) from within the __init__ to trigger the setup of the interface.

This produces exactly the same result as before.

A (very) simple UI designed in Qt CreatorA (very) simple UI designed in Qt Creator

That’s it. Your window is now fully set up. Since the use of a .ui file abstracts out the UI-specific code, you can use this same pattern to load any interface you design.

Martin Fitzpatrick Python GUIs Coaching & Training

1:1 Python GUIs Coaching & Training

Comprehensive code review • Bugfixes & improvements • Maintainability advice and architecture improvements • Design and usability assessment • Suggestions and tips to expand your knowledge • Packaging and distribution help for Windows, Mac & Linux • Find out more.

Adding application logic

You can interact with widgets created through Qt Creator just as you would those created with code. To make things simpler uic adds all child widgets to the window object by their id name as specified in Qt Creator. We’ll cover how to work with these in the next part.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *