Realize a simple interface software based on pyqt5 (radioButton, comboBox, pushButton, picture display)

The pyqt5 usage records involve the basic introduction of pyqt interface controls, use the designer to design the interface ui, and convert it into py code. Regarding the interface, it mainly realizes the mutually exclusive selection event of radioButton, the selection event of comboBox (adding items according to the list), the click event of pushButton, the automatic binding of slot functions, and the drag-in and display of pictures.

1. pyqt environment configuration

1.1 pyqt installation

pip install pyqt5
pip install pyqt5-tools

1.2 pyqt configuration

Find the path of designer.exe under the python environment path

will find the path C:\anaconda\Lib\site-packages\qt5_applications\Qt\bin
Add to the path of the Windows system environment variable path

2. Interface design

2.1 Start Interface Designer

Open the terminal, then enter designer.exe and press Enter to start the pyqt interface designer.
Then click File – “New, find Main Window and select it, and then create a main interface file.

2.2 Controls in pyqt

From the perspective of an unprofessional software engineer, the controls in pyqt can be mainly divided into page layout controls, control containers, button controls, and output controls (display text charts, etc.) from the perspective of front-end page design.

The specific page layout controls are as follows, which include vertical layout, horizontal layout, grid layout, and form layout. The original intention of the page layout is to reduce the difficulty of designing the relationship between controls and controls, and it will force each control to be arranged according to the layout style. Effective nesting is not supported between these page layouts.

The control container is one level lower than the page layout but one level higher than the page controls, and it is rarely used by bloggers. The Group Box in the figure below can have multiple built-in controls of the same group (such as radio boxes or multi-select boxes), the Scroll Area can have a built-in text control for displaying long text, and the Tab Widget can implement multiple tabs (place different controls or page layouts in each tab container)

There are a lot of buttons provided in pyqt, but the blogger thinks that the only important ones are Push Button (ordinary button), Radio Button (radio button, multiple radio buttons need to be placed in the same parent control container when used), Check Button (radio button, multiple radio buttons need to be placed in the same parent control container when used). The effects of other buttons can be achieved through Push Button, such as the command link button.

The input controls provided in pyqt are as follows, including drop-down boxes, text input boxes (single-line, multi-line, rich text), steppers (adjusting values through buttons), time and date selectors, spin buttons, horizontal and vertical drag heads, and horizontal and vertical sliders

There are many page controls in pyqt. Bloggers currently only use image and text display functions, so they only use Label controls (display text, pictures), Text Browser controls (display long text), and Graphics View controls (display sketchpads).

For more common control introductions, please refer to: https://blog.csdn.net/ungoing/article/details/126506569

2.3 Design interface ui

The blogger here plans to implement a calling software for the yolov8 model, and the designed page is as follows. It should be noted that the set comboBox does not specify a default list (because the blogger plans to implement it by reading files). At the same time, for radioButton, you can see that the blogger has prevented it from being placed under the same parent container (mainly see the red framed part in the right picture), and then you can see that the color of the button in the interface is different. In the follow-up development, the blogger modified the graphicsView control to a label control (using the label can display text and pictures, but using the graphicsView code is extremely complicated).

This is because the style properties of the control are set, we can set various properties of the control in the property editor in the lower right corner (mainly font size and color, maximum and minimum width and height restrictions, control color)

In addition to the panel in the lower right corner, you can also set the style of the control by right-clicking on the control and selecting Edit Style Sheet. It should be noted here that what we need to click is the triangle in the picture, not the text, otherwise the effect cannot be set to the target format (such as background color, border color, background image, etc.); in addition, the generated setting result is a css format consisting of key:value;, otherwise an error will be reported.

After the page design is completed, it can be saved as a ui file

3. Implement software

3.1 Using interface files

There are two ways to use the interface ui file, one is to use it directly, and the other is to convert the ui file into a py file and then use it. For details, please refer to:
https://blog.csdn.net/weixin_44452221/article/details/125961228

Use directly to load ui files through PyQt5.uic.loadUi, the complete usage code is as follows. The advantage of using the transfer py file is that the steps are simple, and the ui-py file does not need to be updated every time the UI is modified; the disadvantage is that when binding function events, it is necessary to cooperate with the page designer to find the object name of the ui control. If you want to release the software to the outside world, you need to carefully consider using this method. The ui file cannot be embedded in the executable program, so you need to keep the ui file externally

from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5 import uic

class MyWindows():

    def __init__(self):
        super().__init__()
        #Use the ui file to import and define the interface class
        self.ui = uic.loadUi("mainview.ui")
        self.ui.pushButton.clicked.connect(self.click_test)
        # Initialize interface
        #self.ui.setupUi(self)
    def click_test(self):
        print('I was clicked!')
if __name__ == "__main__":
    app = QApplication([])
    windows = MyWindows()
    windows.ui.show() # remove ui
    app.exec_()

Conversion to py: first convert the ui file to a py file, and then call it in the code. The advantage is that the object name of the ui control can be known during coding, and the configuration of the control can be modified in the ui-py code; the disadvantage is that the ui-py file needs to be regenerated every time the ui file is modified. If you want to release software to the outside world, this method is recommended, because although it is troublesome, you can not expose the ui file to the outside world
1. Execute the following code to convert mainview.ui to mainview.py

python -m PyQt5.uic.pyuic mainview.ui -o mainview.py

2. Execute the following code

from PyQt5.QtWidgets import QMainWindow, QApplication
from mainview import Ui_MainWindow

class MyWindows(QMainWindow):

    def __init__(self):
        super().__init__()
        #Use the ui file to import and define the interface class
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # Initialize interface
        self.ui.pushButton.clicked.connect(self.click_test)
    def click_test(self):
        print('I was clicked!')

if __name__ == "__main__":
    app = QApplication([])
    test = MyWindows()
    test.show() # remove ui
    app.exec_()

After executing the software, the page is shown as below, and the corresponding part of the program can be seen in the lower right corner of the figure below after clicking to start the detection.

3.2 Event binding

For this software development, it involves the use of radioButton, comboBox, and button controls, and also realizes dragging and displaying pictures. All the following codes should be placed in class MyWindows(QMainWindow):.

radioButton selected event implements mutually exclusive selected events. The implementation of the state monitoring function is as follows, only need to be bound to the same processing function (as long as the radioButton is in the same parent container, it will be used naturally to achieve mutual exclusion of page effects).

 self.ui.radioButton.toggled.connect(self.groupBox_click)
        self.ui.radioButton_2.toggled.connect(self.groupBox_click)
        self.ui.radioButton_3.toggled.connect(self.groupBox_click)

The implementation of the radio button group click event is as follows, no matter which button is clicked, the groupBox_click function will be triggered, and then different branch operations can be performed through radioButton.objectName().

    def groupBox_click(self):
        radioButton = self.sender() # Get the control for signal emission
        if radioButton.isChecked() == True:
            #Distinguish different buttons according to radioButton.text()
            #Distinguish different buttons according to radioButton.objectName()
            print(radioButton.text() + " " + radioButton.objectName() + "selected")

pushButton click event This is mainly a button click event, you can use self.ui.pushButton.clicked.connect(self.pushButton_clicked) to bind the control to the event function. You can also use @pyqtSlot() to directly bind the function to the control with the same name. details as follows:

 ## ==== The slot function automatically associated with the signal of the component by connectSlotsByName() =====
    # https://www.cnblogs.com/jgg54335/p/14898742.html
    #Automatically associate the clicked event with the pushButton control
    @pyqtSlot() #If this is not added, it will be triggered twice
    def on_pushButton_clicked(self):
        print(self. ui. pushButton. text())
        if self.ui.pushButton.text()=="Pause detection":
            self.ui.pushButton.setText("Start detection")
            self.ui.pushButton.setStyleSheet("background-color: rgb(134, 217, 255);")
        else:
            self.ui.pushButton.setText( "Pause detection")
            self.ui.pushButton.setStyleSheet("background-color: rgb(250, 12, 32);")

comboBox selected event You need to add item to comboBox first, the specific code is as follows:

 self.ui.comboBox.clear() #clear list
        comblist=["Camera 1","Camera 2","Camera 3","Camera 4","Camera 5","Camera 6"] #list data
        for i in range(len(comblist)):
            self.ui.comboBox.addItem(comblist[i])

The selected event of comboBox is as follows, and its input parameter curText can be used to distinguish the clicked Item

 ## ======= Custom slot function with parameters =======
    @pyqtSlot(str) ##The current item transformation of simple ComboBox
    def on_comboBox_currentIndexChanged(self, curText):
        print(curText)

Picture dragged in and displayed This needs to be set in class MyWindows(QMainWindow) to set its supporting file dragging event, the code is as follows, placed in def __init__(self):

self.setAcceptDrops(True)

The implementation function of file dragging, by judging the file suffix, opening it if it is a picture, and then using self.ui.label.setPixmap(QPixmap(path)) for drawing display.

 def dropEvent(self, evn):
        # print(f'mouse release {evn.posF()}')
        path = evn.mimeData().text()
        if path.lower().endswith((".jpg",".jpeg",".png",".bmp")):
            path=path.replace('file:///','')
            print('file path:\\
' + path)
            #https://blog.csdn.net/weixin_46180132/article/details/118178229
            pixmap = QPixmap(path)
            self.ui.label.setPixmap (pixmap) # display pictures on the label
            self.ui.label.setScaledContents (True) # Make the image adapt to the label size

3.3 Code effect

The effects of various button click events in the software interface are as follows:

The effect of dragging pictures into the software is as follows

The code download link related to this blog post is: https://download.csdn.net/download/a486259/88010473