PyQt4 learning --- hand line and write the code 3 of the interface (series 2)

table of Contents

1. Create a project

2, hands to achieve it

3, detailed snippet


This series of articles antecedent Review:

  1. PyQt4 learning --- the menu bar (addMenu) of 1, the toolbar (addToolBar), TextEdit tool box
  2. PyQt4 learning --- BoxLayout layout 2, the grid GridLayout layout, interface design to achieve Calculator

The previous two sections are paving the way, is to the third chapter, here we are doing a big ticket, the front section of the two to integrate, AI interface to a first experience, the end result is as follows:

1. Create a project

Here accidentally creates a QDialog project, in fact, this relationship is not, here are three groups of project selection for the difference, you can carefully after selecting a project, here on the use of QDialog writing of this project it.

Qt in QMainWindow, QWidget, QDialog difference:

  • QWidget is the base class for all of the graphical interface, which is a subclass of QWidget QMainWindow and are QDialog;
  • QMainWindow is provided a menu, the main window tool bar;
  • QDialog is the dialog box, used for short-term interaction with the user.

Look back at the final results of the previous figure, here we put it wanted to make a beautiful UI little sister for your well-designed, rich design sense UI combination bar, which contains the main controls are as follows:

Finishing point of view, it can be divided into three large pieces:

  1. Printing display output section, defined as left Moreover,
  2. Parameter input portion, defined as right
  3. Function buttons section, defined as a button

(1) The print output section, left contains two

  1. label-- printout
  2. lineEdit-- information display output

(2) parameter input section, right

  1. Learning rate, and other optimizations five label
  2. Corresponding lineEdit, or

(3) three pushbutton function buttons

With so many, we are going to thin line and code that implements the interface to achieve the above functions of it.

2, hands to achieve it

Here is not achieved by one step by step, but rather the entire process is similar to the first display, and a section type, said overview points, as described in further part of our third section. Ado, look global code (intermediate code implementation process has been outlined in several segments that achieve the object, as a comment on the entire portions of code).

__author__ = "lingjun"
# E-mail: [email protected]
# welcome to attention:小白CV

# -*- coding: utf-8 -*-   

from PyQt4 import QtCore
from PyQt4 import QtGui
import sys

QtCore.QTextCodec.setCodecForTr(QtCore.QTextCodec.codecForName("utf8"))

class InputDlg(QtGui.QWidget):
    def __init__(self,parent=None):  
        super(InputDlg,self).__init__(parent)
        QtGui.QWidget.__init__(self,parent=None)
        # self.setGeometry(400,200,640,680)
        self.setWindowTitle(self.tr("自助训练系统"))

        train = QtGui.QPushButton(u'训练开始', self)
        self.connect(train, QtCore.SIGNAL("clicked()"), self.train_slot)    ######################

        test = QtGui.QPushButton(u'测试开始', self)
        self.connect(test, QtCore.SIGNAL("clicked()"), self.main)  #######################

        evaluate = QtGui.QPushButton(u'评估开始', self)
        self.connect(evaluate, QtCore.SIGNAL("clicked()"), self.evaluate_slot)#########################

        # train、test、evaluate水平布局
        bottomLayout = QtGui.QHBoxLayout()
        bottomLayout.addStretch()
        bottomLayout.addWidget(train)
        bottomLayout.addWidget(test)
        bottomLayout.addWidget(evaluate)

        #self.setLayout(bottomLayout)
    ##########################################################################
        label_print = QtGui.QLabel(self.tr("打印输出"))
        self.printTextEdit = QtGui.QTextEdit()

        leftLayout = QtGui.QVBoxLayout()
        leftLayout.addWidget(label_print)
        leftLayout.addWidget(self.printTextEdit)
    ###############################################################################

        label_lr=QtGui.QLabel(self.tr(u"学习率:"))
        label_opt=QtGui.QLabel(self.tr(u"优化方式:"))
        label_me=QtGui.QLabel(self.tr(u"最大迭代数:"))
        label_itr=QtGui.QLabel(self.tr(u"每迭代数保存模型:"))
        label_begin = QtGui.QLabel(self.tr(u"是否从头开始训练:"))

        self.lrLineEdit = QtGui.QLineEdit()

        self.optComboBox = QtGui.QComboBox()
        self.optComboBox.insertItem(0, self.tr("SGD"))
        self.optComboBox.insertItem(1, self.tr("Adam"))

        self.meLineEdit = QtGui.QLineEdit()

        self.itrComboBox = QtGui.QComboBox()
        self.itrComboBox.insertItem(0, self.tr("2"))
        self.itrComboBox.insertItem(1, self.tr("5"))

        self.beginComboBox = QtGui.QComboBox()
        self.beginComboBox.insertItem(0, self.tr("Yes"))
        self.beginComboBox.insertItem(1, self.tr("No"))
        self.checkpointLabel = QtGui.QLabel("0")
        self.connect(self.beginComboBox, QtCore.SIGNAL('currentIndexChanged(int)'), self.retrain_begin_num)

        # 右上侧信息网格布局
        rightLayout = QtGui.QGridLayout()
        rightLayout.addWidget(label_lr,0,0)
        rightLayout.addWidget(self.lrLineEdit,0,1)

        rightLayout.addWidget(label_opt,1,0)
        rightLayout.addWidget(self.optComboBox,1,1)

        rightLayout.addWidget(label_me,2,0)
        rightLayout.addWidget(self.meLineEdit,2,1)

        rightLayout.addWidget(label_itr,3,0)
        rightLayout.addWidget(self.itrComboBox,3,1)

        rightLayout.addWidget(label_begin, 4, 0)
        rightLayout.addWidget(self.beginComboBox, 4, 1)
        rightLayout.addWidget(self.checkpointLabel, 4, 2)
##################################################################
        # 把左部分、右部分、下部分进行网格布局
        mainLayout = QtGui.QGridLayout(self)
        mainLayout.setMargin(15)
        mainLayout.setSpacing(10)
        mainLayout.addLayout(leftLayout, 0, 0)
        mainLayout.addLayout(rightLayout, 0, 1)

        #mainLayout.addLayout(midLayout, 0, 2)
        mainLayout.addLayout(bottomLayout, 1, 0, 1, 2)
        mainLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)

    ########################################################################
    # Button_runs_slot
    ########################################################################
    def retrain_begin_num(self):
        checkpoint_num, ok = QtGui.QInputDialog.getInteger(self,self.tr("checkpoint_num"),
                                       self.tr("请输入模型开始步数:"),
                                       int(self.checkpointLabel.text()),0,150)
        if ok:
            self.checkpointLabel.setText(str(checkpoint_num))



    def test_slot(self):
        button = QtGui.QMessageBox.question(self, "Question",
                                      self.tr("正在测试,等稍等···?"))

    def evaluate_slot(self):
        button = QtGui.QMessageBox.question(self, "Question",
                                      self.tr("正在评估,等稍等···?"))

    def train_slot(self):
        lr_value = self.lrLineEdit.text()  # 获取文本框内容
        print(u'学习率=', lr_value)

        opt_value = self.optComboBox.currentText()  # 返回选中选项的文本
        print(u'优化方式=', opt_value)

        me_value = self.meLineEdit.text()  # 获取文本框内容
        print(u'最大迭代轮数=', me_value)

        itr_value = self.itrComboBox.currentText()
        print(u'每迭代{}保存模型'.format(itr_value))

        begin_value = self.beginComboBox.currentText()
        print(u'是否从0开始训练=', begin_value)

        checkpoint_value = self.checkpointLabel.text()
        print(u'继续训练,Epoch=', checkpoint_value)

        ###### QtGui.QTextEdit() 显示内容 ##########
        self.printTextEdit.setText(u'打印训练参数:\n' + u'学习率: ' + lr_value
                                   + '\n' + u'优化方式: ' + opt_value
                                   + '\n' + u'最大迭代轮数: ' + me_value
                                   + '\n' + u'每迭代步数保存模型: ' + itr_value
                                   + '\n' + u'是否从0开始训练: ' + begin_value
                                   + '\n' + u'继续训练,Epoch: ' + checkpoint_value)

        button = QtGui.QMessageBox.question(self, u"训练,打印学习率",
                                            self.tr("学习率={}".format(lr_value)),
                                            QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel,
                                            QtGui.QMessageBox.Ok)
        if button == QtGui.QMessageBox.Ok:
            self.tr("ok")
        elif button == QtGui.QMessageBox.Cancel:
            self.tr("bay")
        else:
            return

if __name__ == "__main__":
    app=QtGui.QApplication(sys.argv)

    s=InputDlg()
    s.show()
    app.exec_()

3, detailed snippet

Order, from bottom to top

(1) started from the bottom, controls part PushButton, excerpts out here, as follows

        self.setWindowTitle(self.tr("自助训练系统"))

        train = QtGui.QPushButton(u'训练开始', self)
        self.connect(train, QtCore.SIGNAL("clicked()"), self.train_slot)    ######################

        test = QtGui.QPushButton(u'测试开始', self)
        self.connect(test, QtCore.SIGNAL("clicked()"), self.main)  #######################

        evaluate = QtGui.QPushButton(u'评估开始', self)
        self.connect(evaluate, QtCore.SIGNAL("clicked()"), self.evaluate_slot)#########################
  1. The first is to set a window title (setWindowTitle) for the entire GUI interface, all integrated self a little, and when a class, which would be more common in programming after this point is also to keep in mind
  2. Add a " training start button" in PyQt in, QtGui is mainly used for graphical user interface to the GUI (the Graphical the User Interface ) controls in the definition, such as buttons, text boxes. Hi long as it is in the interface can be seen by my mother, is it to be defined; QtCore this is the opposite, in charge of a beautiful flower (former), a charge of content, such as signal transmission section 3
  3. With the button, the button also need to make certain job functions. The following is the use of only the most representative qt signals and slots mechanism, then take a look at a comparison of the image signal slots mechanism of bar chart (below). Train --- we set the button name is; there is a mechanism within the QtCore signal, wherein the trigger here is clicked; transmitting the signal, defined as a function of accepting train-slot function (this function is required in the following definition, we want this button is the definition of dry Diansha)

Function buttons are defined, and that three of them exactly what will be in the form of, or be a pre-arranged, and who who after. There is also need to define ourselves, as follows:

        # train、test、evaluate水平布局
        bottomLayout = QtGui.QHBoxLayout()
        bottomLayout.addStretch()
        bottomLayout.addWidget(train)
        bottomLayout.addWidget(test)
        bottomLayout.addWidget(evaluate)
  1. Examples of a QtGui.QHBoxLayout (), this level is used to layout
  2. The three buttons defined hereinbefore train, test, evaluate using add into
  3. According to the previous idea, is not it should be done, who does what and a addStretch statement? Look at what it means, we turn about: stretching, tension, over-extended, and whose name means the same here, in order to make the format more attractive after the arrangement, and deliberately filled with a blank.

(2) left define display

  1. label-- printout
  2. lineEdit-- information display output

Look, in fact, is this line of thought interfacial setting, not go into details

However, there is little need to pay attention: commonly used methods are addWidget () and addLayout ()

  1. addWidget () for insertion in the layout control
  2. addLayout () for inserting sub-layout in the layout
        label_print = QtGui.QLabel(self.tr("打印输出"))
        self.printTextEdit = QtGui.QTextEdit()

        leftLayout = QtGui.QVBoxLayout()
        leftLayout.addWidget(label_print)
        leftLayout.addWidget(self.printTextEdit)

After the addition is good or needs to be laid, three and 1 is discharged, horizontal layout, this is stackable, vertical arrangement. First instantiated, then add controls into it. It does not seem like very simple to do

(3) a third block portion looked relatively complex, but a closer look, in fact, are substantially similar. Programs like this, looking at the complex, in fact, there is a procedural approach, and it is simply a number.

        label_lr=QtGui.QLabel(self.tr(u"学习率:"))
        label_opt=QtGui.QLabel(self.tr(u"优化方式:"))
        label_me=QtGui.QLabel(self.tr(u"最大迭代数:"))
        label_itr=QtGui.QLabel(self.tr(u"每迭代数保存模型:"))
        label_begin = QtGui.QLabel(self.tr(u"是否从头开始训练:"))

        self.lrLineEdit = QtGui.QLineEdit()

        self.optComboBox = QtGui.QComboBox()
        self.optComboBox.insertItem(0, self.tr("SGD"))
        self.optComboBox.insertItem(1, self.tr("Adam"))

        self.meLineEdit = QtGui.QLineEdit()

        self.itrComboBox = QtGui.QComboBox()
        self.itrComboBox.insertItem(0, self.tr("2"))
        self.itrComboBox.insertItem(1, self.tr("5"))

        self.beginComboBox = QtGui.QComboBox()
        self.beginComboBox.insertItem(0, self.tr("Yes"))
        self.beginComboBox.insertItem(1, self.tr("No"))
        self.checkpointLabel = QtGui.QLabel("0")
        self.connect(self.beginComboBox, QtCore.SIGNAL('currentIndexChanged(int)'), self.retrain_begin_num)
  1. Disposable label all the necessary parts are added to it
  2. This control is left to the user's own input, it can be defined as LineEdit, may be empty by default; there is such a selective ComboBox behind (the drop-down list boxes), set optional stuff, here inserted projects (Terms) ; this mainly involves two, not much else to say
  3. A little different place, pull-down list box that can be set into the signaling mechanism, the above code is set to "when the current index change, let him transmit signals, activated slot function retrain_begin_num"
  4. Since the right part, the vertical direction is also horizontal, it is using it in a mesh form on the line layout, (setting the reference herein: the PyQt4 learning --- a BoxLayout layout 2, the grid layout GridLayout achieve calculator interface design ) as described in this such:
        # 右上侧信息网格布局
        rightLayout = QtGui.QGridLayout()

        # addWidget用于在布局中插入控件
        # QGridLayout.addWidget(窗体, 起始行, 起始列, 占用行, 占用列, 对齐方式)
        rightLayout.addWidget(label_lr,0,0)
        rightLayout.addWidget(self.lrLineEdit,0,1)

        rightLayout.addWidget(label_opt,1,0)
        rightLayout.addWidget(self.optComboBox,1,1)

        rightLayout.addWidget(label_me,2,0)
        rightLayout.addWidget(self.meLineEdit,2,1)

        rightLayout.addWidget(label_itr,3,0)
        rightLayout.addWidget(self.itrComboBox,3,1)

        rightLayout.addWidget(label_begin, 4, 0)
        rightLayout.addWidget(self.beginComboBox, 4, 1)
        rightLayout.addWidget(self.checkpointLabel, 4, 2)

(4) in front of three elements, namely the level of the bottom part of the layout, the left part of the vertical layout, the right part of the grid layout, can be said that the more commonly used qt remember layout encompasses both and finally, or is to be presented on the entire interface, or do not know the relationship between them three, three of them here should be a clear definition of the relationship, as follows:

  • addLayout () for inserting sub-layout in the layout
        # 把左部分、右部分、下部分进行网格布局
        mainLayout = QtGui.QGridLayout(self)
        mainLayout.setMargin(15) # 表示控件与窗体的左右边距
        mainLayout.setSpacing(10) # 表示各个控件之间的上下间距
        mainLayout.addLayout(leftLayout, 0, 0)
        mainLayout.addLayout(rightLayout, 0, 1)

        #mainLayout.addLayout(midLayout, 0, 2)
        mainLayout.addLayout(bottomLayout, 1, 0, 1, 2)
        mainLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize) # 设置对话框大小固定,不允许用户改变

(5) a function of the groove portion implemented


He said main GUI data box next to get it, and then print to the display box. This would be more common after application

    def train_slot(self):
        lr_value = self.lrLineEdit.text()  # 获取文本框内容
        print(u'学习率=', lr_value)

        opt_value = self.optComboBox.currentText()  # 返回选中选项的文本
        print(u'优化方式=', opt_value)

        me_value = self.meLineEdit.text()  # 获取文本框内容
        print(u'最大迭代轮数=', me_value)

        itr_value = self.itrComboBox.currentText()
        print(u'每迭代{}保存模型'.format(itr_value))

        begin_value = self.beginComboBox.currentText()
        print(u'是否从0开始训练=', begin_value)

        checkpoint_value = self.checkpointLabel.text()
        print(u'继续训练,Epoch=', checkpoint_value)

        ###### QtGui.QTextEdit() 显示内容 ##########
        self.printTextEdit.setText(u'打印训练参数:\n' + u'学习率: ' + lr_value
                                   + '\n' + u'优化方式: ' + opt_value
                                   + '\n' + u'最大迭代轮数: ' + me_value
                                   + '\n' + u'每迭代步数保存模型: ' + itr_value
                                   + '\n' + u'是否从0开始训练: ' + begin_value
                                   + '\n' + u'继续训练,Epoch: ' + checkpoint_value)

OK, get away, here today friends

White CV: Public Number aims to focus on CV (computer vision), AI (artificial intelligence) technology-related fields, the main content of the article around the C ++, Python programming techniques, machine learning (ML), the depth of learning (DL), OpenCV image processing, etc. technology, explore the depth of technical points, study and work record common operations, problems do you learn to work assistant. Only concerned with technology, the professional knowledge sharing platform CV field.
 

 

 

Published 74 original articles · won praise 64 · views 130 000 +

Guess you like

Origin blog.csdn.net/wsLJQian/article/details/99976078