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
insert image description here

Add the found path C:\anaconda\Lib\site-packages\qt5_applications\Qt\bin
to the path of the Windows system environment variable path
insert image description here

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.
insert image description here

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.
insert image description here
The control container is one level lower than the page layout but one level higher than the page controls, and bloggers rarely use it. 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 built-in text controls for displaying long text, and the Tab Widget can implement multiple tabs (in each tab Place different controls or page layouts in the container)
insert image description here

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, when using it, multiple radio buttons need to be placed in the same parent control container), Check Button (single button, need to put multiple radio buttonn in the same parent control container when using). The effects of other buttons can be achieved through Push Button, such as the command link button.
insert image description here
The input controls provided in pyqt are as follows, including drop-down box, text input box (single line, multi-line, rich text), stepper (adjust the value through buttons), time and date selector, rotation button, horizontal and vertical drag heads , Horizontal and vertical sliders
insert image description here
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 (Show Artboard).
insert image description here

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), and for the radioButton, it can be seen that the blogger has prevented it from being placed under the same parent container (mainly see the right picture The part framed in red), 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).
insert image description here
This is because the style properties of the control are set, we can set various properties of the control (mainly font size and color, maximum and minimum width and height restrictions, control color) in the property editor in the lower right corner. In addition to the panel in the lower right corner, you can
insert image description here
also Style 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.
insert image description here
After the page design is completed, it can be saved as a ui file

3. Realize the 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

Direct use Use PyQt5.uic.loadUi to load ui files, and 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.若要对外发布软件,使用这种方法需要慎重考虑,ui文件无法嵌入到可执行程序中,需要对外保留ui文件

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

class MyWindows():

    def __init__(self):
        super().__init__()
        # 使用ui文件导入定义界面类
        self.ui  = uic.loadUi("mainview.ui")
        self.ui.pushButton.clicked.connect(self.click_test)
        # 初始化界面
        #self.ui.setupUi(self)
    def click_test(self):
        print('我被点击了!')
if __name__ == "__main__":
    app = QApplication([])
    windows = MyWindows()
    windows.ui.show() # 去掉ui
    app.exec_()

Convert py to use : 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. 若要对外发布软件,推荐使用这种方法,因为虽然麻烦,但可以不对外暴露ui文件
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__()
        # 使用ui文件导入定义界面类
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # 初始化界面
        self.ui.pushButton.clicked.connect(self.click_test)
    def click_test(self):
        print('我被点击了!')

if __name__ == "__main__":
    app = QApplication([])
    test = MyWindows()
    test.show() # 去掉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.
insert image description here

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 are to be placed class MyWindows(QMainWindow):in .

radioButton selection event Implement mutually exclusive selection 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() # 获得信号发射的控件
        if radioButton.isChecked() == True:
            #根据radioButton.text()来区分不同的按钮
            #根据radioButton.objectName()来区分不同的按钮
            print(radioButton.text() +"  "+radioButton.objectName()+ "被选中")

pushButton click event This is mainly a button click event, which can be used to self.ui.pushButton.clicked.connect(self.pushButton_clicked)bind controls and event functions. It is also possible to @pyqtSlot()directly bind a function to a control of the same name. details as follows:

    ## ====由connectSlotsByName()自动与组件的信号关联的槽函数=====
    # https://www.cnblogs.com/jgg54335/p/14898742.html
    #自动与 pushButton 控件进行clicked 事件的关联   
    @pyqtSlot() #不加这个会被触发两次
    def on_pushButton_clicked(self):
        print(self.ui.pushButton.text())
        if self.ui.pushButton.text()=="暂停检测":
            self.ui.pushButton.setText( "开始检测")
            self.ui.pushButton.setStyleSheet("background-color: rgb(134, 217, 255);")
        else:
            self.ui.pushButton.setText( "暂停检测")
            self.ui.pushButton.setStyleSheet("background-color: rgb(250, 12, 32);")

ComboBox selection event First you need to add item to comboBox, the specific code is as follows:

        self.ui.comboBox.clear() #清除列表
        comblist=["摄像头1","摄像头2","摄像头3","摄像头4","摄像头5","摄像头6"] #列表数据
        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

    ## =======自定义带参数的槽函数=======
    @pyqtSlot(str) ##简单的ComboBox的当前项变换
    def on_comboBox_currentIndexChanged(self,curText):
        print(curText) 

Image drag-in display This needs to class MyWindows(QMainWindow)set its supporting file drag-in event in the settings, the code is as follows, placed def __init__(self):in

self.setAcceptDrops(True)

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

    def dropEvent(self, evn):
        # print(f'鼠标放开 {evn.posF()}')
        path = evn.mimeData().text()
        if path.lower().endswith((".jpg",".jpeg",".png",".bmp")):
            path=path.replace('file:///','')
            print('文件路径:\n' + path)
            #https://blog.csdn.net/weixin_46180132/article/details/118178229
            pixmap = QPixmap(path)
            self.ui.label.setPixmap (pixmap)  # 在label上显示图片
            self.ui.label.setScaledContents (True)  # 让图片自适应label大小

3.3 Code effect

The effect of various button click events in the software interface is as follows:
insert image description here
the effect of dragging the picture into the software is as
insert image description here
follows

Guess you like

Origin blog.csdn.net/a486259/article/details/131564563