PYQT5|Pyside2 UI Designer Qt Designer dynamically loads UI files

PYQT5|Pyside2 UI Designer Qt Designer dynamically loads UI files

Introduction to Qt Designer

Click here to watch the video explanation and learn the following

The windows and controls of the QT program interface are created with the corresponding code as above.

However, it is difficult to write the interface in your mind directly in code.

Many times, what we look like at runtime is not what we want. Often, we also modify the code to adjust the location of controls on the interface and run the preview. Repeat this many times.

But that's true. It's too much trouble.

In fact, we can use the QT interface generator   Qt Designer  , Drag and drop to visually create a general program interface.

How do I run this tool?

Under Windows, run the Python installation directory   Scripts\pyside2-designer.exe   This executable

If you have pyqt5 installed, run the Python installation directory   Scripts\pyqt5designer.exe   This executable

From the video instructions linked above, you can get a first look at how to use Qt Designer.

The interface designed by Qt Designer is ultimately saved in a ui file.

You can open this ui file and see that it is an interface definition in XML format.

Dynamic loading of UI files

Click here to watch the video explanation and learn the following

With an interface definition file, our Python program can load UI definitions from the file and dynamically create a corresponding window object.

The following:

from PySide2.QtWidgets import QApplication, QMessageBox
from PySide2.QtUiTools import QUiLoader

class Stats:

    def __init__(self):
        # Load UI definitions from a file

        # Dynamically create a corresponding window object from the UI definition
        # Note: the control object inside also becomes a property of the window object
        # Examples include self.ui.button, self.ui.textEdit
        self.ui = QUiLoader().load('main.ui')

        self.ui.button.clicked.connect(self.handleCalc)

    def handleCalc(self):
        info = self.ui.textEdit.toPlainText()

        salary_above_20k = ''
        salary_below_20k = ''
        for line in info.splitlines():
            if not line.strip():
                continue
            parts = line.split(' ')

            parts = [p for p in parts if p]
            name,salary,age = parts
            if int(salary) >= 20000:
                salary_above_20k += name + '\n'
            else:
                salary_below_20k += name + '\n'

        QMessageBox.about(self.ui,
                    'Statistical Results',
                    f'''Those with salaries over 20,000:\n{salary_above_20k}
                    \n Those below 20,000 are:\n{salary_below_20k}'''
                    )

app = QApplication([])
stats = Stats()
stats.ui.show()
app.exec_()

If you are using PyQt5 instead of PySide2, the code to load the UI file is as follows

from PyQt5 import uic

class Stats:

    def __init__(self):
        # Load UI definitions from a file
        self.ui = uic.loadUi("main.ui")

Convert UI files to Python code

There is also a way to use UI files: first convert the UI files directly into Python code files that contain interface definitions, then use the classes that define the interfaces in your programs

  1. Perform the following command to convert the UI file directly into a Python code file containing the interface definition
pyside2-uic main.ui > ui_main.py

If you have PyQt5 installed, perform the Command transformation in the following format

pyuic5 main.ui > ui_main.py

Then use the class that defines the interface like this in your code file

from PySide2.QtWidgets import QApplication,QMainWindow
from ui_main import Ui_MainWindow

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        # Use ui file to import definition interface class
        self.ui = Ui_MainWindow()
        # Initialization interface
        self.ui.setupUi(self)

        # Controls defined using the interface are also accessed from within the ui
        self.ui.webview.load('http://www.baidu.com')

app = QApplication([])
mainw = MainWindow()
mainw.show()
app.exec_()

So which way should we use better? Dynamic loading or converting to Python code?

White Moon Black Feather suggests: It is usually convenient to use dynamic loading, because after changing the interface, there is no need for conversion, and it runs directly, which is especially convenient.

However, if you have controls in your program that are not provided by qt designer, then you need to add some extra declarations to your code, and there may be strange problems. Python code is often transformed.

An exercise

Please use Qt Designer to implement a similar   Postman   HTTP interface test tool.

The interface is as follows

To achieve the function, Click here to view the video instructions

Common controls are used in this interface: buttons, single-line text boxes, multiple-line text boxes, combination selection boxes, tables.

You can start with the following sections of this tutorial by selecting the boxes and tables for friends you have not met.   Common Control 2  .

If you are unfamiliar with sending HTTP requests in Python, you can start with the interface.

Then? Click here to learn the HTTP Requests tutorial for White Moon Black Feather After that, do it again.

Tourist   You can also do this exercise and get the reference code. Click here to view

Interface Layout

Click here to watch the video explanation and learn the following

There's a problem with the interface program we wrote earlier. If you zoom by dragging the lower right corner of the main window border with your mouse, you'll find that the controls inside remain the same size. It would be ugly.

We usually want the distances between controls in the interface to scale as the main window scales.

Qt accomplishes this by laying out the Layout class on the interface.

There are four Layout layouts that we use most, one for each

  • QHBoxLayout horizontal layout

QHBoxLayout places the controls horizontally and horizontally from left to right, as shown below

  • QVBoxLayout Vertical Layout

QHBoxLayout places the controls vertically from top to bottom, as shown below

  • QGridLayout Table Layout

QGridLayout places multiple controls in a grid, some of which can occupy multiple grids, as shown below

  • QFormLayout Form Layout

The QFormLayout form is like a two-column form and is ideal for filling out an interface of this type, such as a registration form, as shown below

Layout example

See the video instructions for layout s.

MainWindow's Layout

If the main window we choose is of MainWindow type, to set Layout for MainWindow as a whole, we must   Add a control below the centralwidget first  , as follows

Then you can right-click MainWindow and select the layout as follows

Adjust control position and size

Click here to watch the video explanation and learn the following

Scale the size of controls in a layout

You can adjust it by setting the sizePolicy of the control. See the video for instructions.

Adjust control spacing

To adjust the spacing between the top and bottom of the control, add layout to the control, and then adjust the spacing by setting padding and margin above and below the layout. See the video for instructions.

To adjust the spacing between the left and right of the control, you can either add a horizontal spacer or layout's left and right margin s

Adjust Control Order

Sometimes we need to adjust the order in which controls are displayed up and down or left and right in a layout. What can we do?

If you have two simple controls inside the layout, you usually just drag them directly.

But if it's more complex, like,

everybody click here , download the program interface code developed by a white moon black feather actual class student, unzip, and drag the main.ui interface file inside to the Qt designer.

If we want to make some changes to the original interface, as shown in the figure below

You can try to create a new vertical layout yourself by dragging the original two layouts into the vertical layout.

You will find that if you want to adjust the display order of the two layout s, direct dragging often results in confusing interfaces.

What shall I do?

The explanations in this section are visible only to internal trainees

Interface Layout Steps Recommendation

Click here to watch the video explanation and learn the following

The experience with laying out interface controls is to follow these steps

  • Place all controls in place on the interface without using any Layout first

  • Then start with the innermost layer to set the Layout of the control

  • Gradually expand to outer layers for Layout settings of controls

  • Finally, adjust the size ratio of the controls in the layout, using Layout's layoutStrentch property first to control

Jump from one window to another

Frequently a friend asks me what to do if a window (such as a login window) is displayed at the beginning of the program and then goes to another window after the operation.

The main way is to instantiate another window, display a new one, and close the old one.

As shown in the following code

from PySide2 import QtWidgets
import sys

class Window2(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()
        self.setWindowTitle('Window 2')

        centralWidget = QtWidgets.QWidget()
        self.setCentralWidget(centralWidget)

        button = QtWidgets.QPushButton('Button 2')

        grid = QtWidgets.QGridLayout(centralWidget)
        grid.addWidget(button)


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Window 1')

        centralWidget = QtWidgets.QWidget()
        self.setCentralWidget(centralWidget)

        button = QtWidgets.QPushButton('Open a new window')
        button.clicked.connect(self.open_new_window)

        grid = QtWidgets.QGridLayout(centralWidget)
        grid.addWidget(button)

    def open_new_window(self):
        # Instantiate another window
        self.window2 = Window2()
        # Show New Window
        self.window2.show()
        # Close yourself
        self.close()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Click here to download   A sample code package for switching logins to the main window

If you often have to jump back and forth between two windows, you can use   hide()   Method hides the window instead of   closes()   Method Closes the window. Another benefit is that when the hidden window is shown again, the original operation is saved and will not disappear.

Pop-up Mode dialog

Sometimes we need to pop up a modal dialog box to enter some data and then go back to the original window.

The so-called Mode dialog box means that after popping up this dialog box, the original window is in an inoperable state and can only continue when the Mode dialog box is closed.

Refer to the following code

from PySide2 import QtWidgets
import sys

class MyDialog(QtWidgets.QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('model dialog box')

        self.resize(500, 400)
        self.textEdit = QtWidgets.QPlainTextEdit(self)
        self.textEdit.setPlaceholderText("Please enter payroll")
        self.textEdit.move(10, 25)
        self.textEdit.resize(300, 350)

        self.button = QtWidgets.QPushButton('Statistics', self)
        self.button.move(380, 80)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('main window')

        centralWidget = QtWidgets.QWidget()
        self.setCentralWidget(centralWidget)

        button = QtWidgets.QPushButton('Open Mode Dialog')
        button.clicked.connect(self.open_new_window)

        grid = QtWidgets.QGridLayout(centralWidget)
        grid.addWidget(button)

    def open_new_window(self):
        # Instantiate a dialog class
        self.dlg = MyDialog()        
        # Show the dialog box, where the code is blocked,
        # Wait for the dialog box to close before continuing
        self.dlg.exec_()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Exercises

VIP actual class students please contact the teacher to complete a data sampling program development, the interface is as follows

Tourist   You can also do this exercise and get the reference code. Click here to view

Keywords: Python PyQt5 PySide2

Added by xcali on Wed, 08 Dec 2021 19:29:36 +0200