Pyqt5 is a GUI interface program development of Pyhon, for testing, to understand and master it, can be conducive to understanding the development of the front and back end projects, but also can use it to do a small tool, QT Designer interface design tool to quickly design the desired interface, put the focus on logic development. For no development experience of the test, very suitable, master can be used to learn scattered Python knowledge to write programs.

Without further ado, I will introduce pyQT5

one , Pyqt5 Environment set up

1 . Install pytqt 5 Library, and pyside 2 library

pip install pyqt5 -i pypi.douban.com/simple 

pip install PySide2 -i pypi.douban.com/simple/ –trusted-host pypi.douban.com

2 . Pycharm associates the QtDesigner tool with PyQt5 Uic conversion tool

The qtDesigner path selects Designer from Pyside2 in site-Packages

Pyqt5uic Path selection script pyuic5.exe

$FileName$ -o $FileNameWithoutExtension$_UI.py
$FileDir$
Copy the code

Pyuic5 -o xx.py xx. UI is executed in the current path

3. Open Designer and UI file conversion in Pycharm

Second, basic code structure

Goal: Separation of interface code and logic.

1. Use desinger interface design and save the UI file

Note: Select Widget when creating a new one

2. Ui file to py file, resulting in the following

Add the following code, you can run the interface program

if __name__ == '__main__':     
    import sys                                            
    app = QtWidgets.QApplication(sys.argv)                   
    Window = QtWidgets.QWidget()        Create a window
    ui = Ui_Form()                      Get the UI object
    ui.setupUi(Window)                  # represents the UI interface, loaded into this window
    Window.show()                       # Display interface
    sys.exit(app.exec_())
Copy the code

   

3. Write the logical code for the interface

Qtwidgets. QMainWindow; qtwidgets. QMainWindow;


```js
from PyQt5.Qt import *
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from test_case.test import Ui_Form
class Login(QWidget,Ui_Form):
    def __init__(self,parent=None,*args,**kwargs):
        super().__init__(parent,*args,**kwargs)
        self.setupUi(self)
        self.func_list()
    def func_list(self):
        self.func()
    def func(self):
        pass
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Login()
    window.show()
    sys.exit(app.exec_())
Copy the code

Tip, you can set up a real-time code for the above code:

4. Write the main program code

A program is not only an interface, the main program code to control the display of which interface

Third, QObject class

1 . Everything inherits from O bject Object class* * * *

Each object has a unique objectName, which can be found in desiner.

[inherits(” class A “)] # if an instance is inherits from class A

ObjectName must be set for buttons, labels, and Windows

If it’s a UI file set by Designer, convert it to py file, self. ObjectName represents that control as follows:

Related codes:

SetProperty ('level1', 'first ') setProperty(' Level2 ', 'Second ') object. Property (' Level1 ') # Get the value object of a property set. DynamicPropertyNames () # Get the object of all properties set by setPropertyCopy the code

This involves the ID selector in the QSS style, and the property selector.

2. Common method for everything (controls, etc.) – delete

Destroyed. Connect (lambda: print(‘ object is released ‘)) if you want to delete a control, use the.deletelater () object.

3. Common method for everything (controls, etc.) – timer

Use time_id= object. StartTimer (1000) to set the timer object with the interval of 1 second under the class to override the event timerEvent(), which can set the timer to do. KillTimer (time_id) # is a basic example of a timer object

from PyQt5.Qt import *
import sys
class Obj2(QObject) :def timerEvent(self.QTimerEvent): # override event (special parameter used to connect things)print(QTimerEvent)
        print(" I'm the other oneQbjectInheriting class timer events ")if __name__ = ='__main__':
    app = QApplication(sys.argv)
    window = QWidget()
    obj2=Obj2()
    obj2.startTimer(2000KillTimer (timer_id) # obj2.killTimer(timer_id)window.show()
    sys.exit(app.exec_())
Copy the code

If you want to set a timer for a label or button, write your own child control class, label or button

Label Set timer case

Because the timerEvent is overridden in the child tag class, any object that is a word tag class can use this timer

from PyQt5.Qt import *
import sys
class Window(QWidget) :def __init__(self) :super().__init__() # call the parent classQWidgetIn theinitmethodsself.setWindowTitle(" Software Name ")self.resize(600, 500)
class Label(QLabel) :def __init__(self, *args, * *kwargsThis can accept various parameterssuper().__init__(*args, * *kwargs) # preserve the methods of the parent classself.resize(80, 40)
        self.move(# 100, 100)self.setText(' 10 ')self.setStyleSheet("background-color: #.CDB9; font-size:25pxSelf.timer_id = self.starttimer (1000) def setSec(self, SEC): Self. setText(STR (SEC)) def ms(self,ms): self.setText(STR (SEC)) def ms(self,ms): self.timer_id = self.startTimer(ms) def timerEvent(self, *args, **kwargs): SEC = int(self.text()) # count down SEC -= 1 self.settext (STR (SEC)) # count down SEC -= 1 Self. killTimer(self.timer_id) #timer_id is a global variable, so we can use if __name__ == '__main__': App = QApplication(sys.argv) window = window () label = label (window) label.setsec (20) # set initial time label.ms(1000) # set jump time #  timer_id = label.startTimer(1000) # # label.killTimer(timer_id) window.show() sys.exit(app.exec_())Copy the code

The following is a useless example of a button that can be clicked periodically

Four,Events, signals and slots (actions)

To complete an operation on a program, you need to use the mouse and keyboard to control certain events in the program,

When the event is triggered, it releases some of the default signals, or you can customize the signals,

Signals are used to trigger the next action, the signals and slots at the heart of PyQT5.

 

1. The event

Example: some events of the button class QPushButton.

There’s click, double click, press, release, etc.

To view the event code click QPushButton to view the event

Qtdesiner can also look at the signal and guess what events there are

View the following effect

1. You can see that the program will first distribute to the Event method and then from there

  1. You can modify the press and double click events
from PyQt5.Qt import *
import sys

class Window(QWidget) :def __init__(self) :super().__init__(a)self.setWindowTitle(' Event mechanism ')self.resize(600, 450)
        self.move(300, 300)
class Btn(QPushButton) :def __init__(self, *args, * *kwargs) :super().__init__(*args, * *kwargs)
        self.move(60, 60)
        self.resize(50, 35)
        self.setText(' button control ')self.setStyleSheet('background-color:green') # # rewriteeventmethodsdef event(self.evt): # The previous function was to distribute to different signals #print(evt"Any signal has to go througheventMethod ","WWWWWWWWWW')
        return super().event(evt* * * * * * * * * * * * * *def mousePressEvent(self.evt) : #print(" Mouse button event ")return super().mousePressEvent(evt) # distribute the same method from the parent downdef mouseDoubleClickEvent(self.evt) :print(" double-click ")return super().mouseDoubleClickEvent(evt)
if __name__ = ='__main__':
    app = QApplication(sys.argv)
    window = Window()
    btn = Btn(window)
    window.show()
    sys.exit(app.exec_())
Copy the code

Of course, there are also some events, such as the right mouse click event, a simple look at the effect as follows:

class Window(QWidget) :def __init__(self) :super().__init__(a)self.setWindowTitle(' Event mechanism ')self.resize(600, 450)
        self.move(300, 300)
    def contextMenuEvent(self.evt): # rewrite the method with the correct nameprint(" Right click in window ")return super().contextMenuEvent(evt)
Copy the code

Take advantage of this, combined with QMenu can be realized after right click menu function. The timer mentioned in Qobject is also an event.

2. Signal and transmission parameters

The signal may be released with or without parameters. Such as:

A. When the radio button performs a click event, it can pass the Bool value of whether it is selected when clicked

B. After the text input box is edited and closed, the edited text (STR format) will be passed.

C. Multi-select box. When switching the option event, the selected text (STR) will be passed when the current text changes the signal.

D. Digital regulator, when adjusting the value, the value changes the signal, the transmission value (the transmission can be plastic, can also be text) in qtdesiner, you can go to view the signals of different controls, and the parameters to be transmitted by the signal

For example, when the numeric step size regulator changes the signal, the text can pass the integer or the string, and the brackets [] can be added after the signal. It is written as follows:

self.qsb.valueChanged[int].connect(lambda val: Print (type(val)) # print(type(val)) # print(type(val)) # print(type(val)) # print(type(val)) # print(type(val)Copy the code

Custom signal

Emit a signal from pyqtSignal().emit() by changing the event method.

For example, in the button subclass, change the button button event (to right mouse button down)

class Btn(QPushButton): # right-click signalrightSignal Def mousePressEvent(self, evt) = pyqtSignal() def mousePressEvent(self, evt):superMousePressEvent (evt) # print(evt.button()) # print(evt.button()1Right click yes2
        # print(evt)     #<PyQt5.QtGui.QMouseEvent object at 0x0000022ED32583A8< span style = "max-width: 100%; clear: both; min-height: 1em2Right click #if evt.button() == 2: # qt. RightButton also represents2
        ifEvt.button () == qt. RightButton: #2
            # print('Right mouse button pressed'Self.rightsignal. emit() # This is used to test whether the right click function works, not the function self.rightsignal. emit() # This is used to test whether the right click function worksCopy the code

The above example, do not care about, then look at the signal transfer parameters, understand good, convenient for the control of confidence to understand

A. Define the signal (indicates the type of data that the signal can emit)

i. rightSignal = pyqtSignal([str],[str,int])  
Copy the code

B. Release the signal (which type of parameter to pass, write [] after the signal object) as follows

I. self. RightSignal [STR,int].emit(" one parameter ",555)Copy the code

C. Signal connection slot function (when used, also write which type, can release which signal), as follows

I. Btn.rightsignal [STR,int].connect(slot function) ii. Btn.rightsignal [STR].connect(slot function)Copy the code

The decorator implements signal and slot connections, but there is no research on whether other signals also work: a simple example is as follows:

3. The slot function

If the signal sends parameters, when you define the slot function, the corresponding slot function needs to be able to receive,

That is, the defined slot function needs to pass parameters as follows

Def get_msg(a,b) pass def get_msg2(a) pass sendmsged[STR,int].connect(get_msg2)Copy the code

Four,QWidget

Common event

1. Window events

  1. QWidget has window events that you can re-create to see the effect when you subclass QWidget

Window opening event showEvent,

CloseEvent Event,

Window resizeEvent

2. Mouse events

2. Some mouse events for QWidget, as shown in the following example

Press mousePressEvent, release mouseReleaseEvent,

Double-click mouseDoubleClickEvent and move the mouse to mouseMoveEvent

Mouse over enterEvent,

Mouse away from leaveEvent

Right-click contextMenuEvent

from PyQt5.Qt import *
import sys
class Window(QWidget) :def __init__(self) :super().__init__(a)self.setWindowTitle(" Get and set control size, size, and control size limits ")self.resize(600500).self.func_list(a)def enterEvent(self.QEvent) :print(' mouse entry event ')self.setStyleSheet("background-color:red;") def leaveEvent(self, QEvent): print(' cursor left event ') self.setstylesheet (")background-color:green;") def contextMenuEvent(self, evt): super(). ContextMenuEvent (evt)Right-click in the window") print(evt) def func_list(self): self.func() def func(self): pass if __name__ == '__main__': app = QApplication(sys.argv) window = Window() """Set the mouseMoveEvent to ---- without pressing the mouse. It can also track movement with the mouse""" # window.setMouseTracking(True) window.show() sys.exit(app.exec_())Copy the code

Click the event to get the location of the click from evtent

3. Keyboard events

In a Qwidget subclass, need to rewrite the event, noted that joining together with | virtual key, joining together solid use the and keys

Def keyPressEvent(self, QKeyEvent):if QKeyEvent.key() == Qt.Key_5:     #
            print('Press 5')
        if QKeyEvent.modifiers() == Qt.ControlModifier and QKeyEvent.key() == Qt.Key_C:
            print('press CTRL + c') # CTRL + shift + c (the two virtual keys using or real key | splicing and)if QKeyEvent.modifiers() == Qt.ControlModifier | Qt.ShiftModifier and QKeyEvent.key() == Qt.Key_C:
            print('ctrl+ shift+ c')
        print("Press anything."Def keyReleaseEvent(self, QKeyEvent): print()'release')
Copy the code

Commonly used method

Object. SetMinimumSize (200.200) # allow minimum size objects. SetMaximumSize (500.600) # Allow maximum size objects. SetGeometry (50.200.60.30) # Set position and size object.. setContentsMargins(50.50.10.0Print (label. ContentsRect ()) print(label. ContentsRect ()) Size) label2.lower() # to the bottom see figure (hierarchy) label1.raise_() # to the top label2.stackUnder(label1) # object2In the object1ChildAt (2.2) # viewwindow(2.2ParentWidget () # View its parent control object. childrenRect() # Get all child controls relative to their own boundariesCopy the code

Common methods series 2

# btn.setenabled (False) # Btn.setVisible (False) # Show # btn.sethidden (False) # Hide #window.show() # show, parentwindowDisplay, child control buttons also display #window.hide() # Hide main window btn.hide() # Hide button"""Allow string [*] in title to be displayed as *"""
window.setwindowModified (True) #"""Active or not?"""
window1.show()
window.show() # print()windowPrint (Window1.isActiveWindow ()) self.setwinDowFlags (qt.framelessWindowhInt) #Copy the code

Mouse Style Settings

Custom ICONS: Use QPixmap and QCursor

pixmap= QPixmap('aaa.png')
new_pixmap = pixmap.scaled(20.20# set cursor size = QCursor(new_pixmap,1.1) # represents an excessive range of mouse styleswindow.setCursor(cursor)
Copy the code

Set the maximize minimize button

If you want to have something that has no borders, that has no top part, it can’t be dragged, it can’t be maximized, it can’t be minimized, so you define it yourself

Self. setWindowFlags(Qt.FramelessWindowHint) # set to no border

The code to use is as follows

Button related close () closes showMinimized () Self.showmaximized () Maximized self.ismaximized () Minimized self.showmaximized () minimized Self.shownormal () # select * from self.shownormal () Mouse button under the record of relative coordinates and global coordinates mouse movement, find the global coordinates after the move, calculate the amount of movement, let the relative coordinates move release event, let the move under a mark, mouse release, let itCopy the code

And I’m going to set transparency

from PyQt5.Qt import *
import sys
class Window(QWidget) :def __init__(self, *args, * *kwargs) :super().__init__(*args, * *kwargs)
        self.setWindowFlags(Qt.FramelessWindowHint) # no bordersself.setWindowOpacity(0.7) # translucency, must be floating point typeself.setWindowTitle(' Window case ')self.resize(600, 450)

        self.mouse_press = False # initial tag, change tag # self.move(300.300)
        self.btn_w = 50
        self.btn_x = 20self.func_list() def func_list(self): self.btn() def btn(self): Self. close_btn = QPushButton(self) self. close_btn.settext ('off')
        self.close_btn.resize(self.btn_w, self.btn_x)

        self.max_btn = QPushButton(self)
        self.max_btn.setText(maximization)
        self.max_btn.resize(self.btn_w, self.btn_x)
        self.min_btn = QPushButton(self)
        self.min_btn.setText(Minimize) self.min_btn.resize(self.btn_w, Self.btn_x) self.close_btn.pressed. Connect (self.close) # def max_signal():ifSelf.shownormal () self.max_btn.settext () self.shownormal () self.max_btn.settext ()maximization)
            elseSelf.showmaximized () self.max_btn.settext () self.showmaximized () self.max_btn.settext ()'recovery') self.max_btn.pressed. Connect (max_signal) self.min_btn.pressed. Connect (self.showNotifyIcon) # Minimized minimized display signal"""If the window size changes, it can also change freely."""
    def resizeEvent(self, QResizeEvent):
        self.close_btn.move(self.width() - 50.2)
        self.max_btn.move(self.width() - 100.2)
        self.min_btn.move(self.width() - 150.2)

    """Mouse down to record starting position."""
    def mousePressEvent(self, QMouseEvent):
        ifQMouseEvent.button() == Qt.LeftButton: Self.win_x = self.x() # Self.win_y = self.y() # self.win_y = self.y Self.m_x = qMouseEvent.globalx () # Self.m_y = qMouseEvent.globaly () #1.Create a flag to determine that the mouse can only move # after it is pressed2.The window's original coordinates #3.Coordinates of the mouse down"""Mouse movement moves the starting position of the press based on the amount of global coordinate movement."""
    def mouseMoveEvent(self, QMouseEvent):
        ifself.mouse_press: Move_x = qmouseEvent.globalx () # move_y = qmouseEvent.globaly () # move_x = self.m_xyy = move_y - self.m_y self.move(self.win_x + xx, self.win_y + yy) #ifWindow flag == True: #2.Calculate movement according to the mouse pressed point #3.Based on the amount of movement and the original coordinates of the window, the new coordinate # is obtained4.Move window position"""When released, change the flag to False so that it will not move when pressed."""
    def mouseReleaseEvent(self, QMouseEvent):
        self.mouse_press = False
        # 1.Reset the tag created in mousePressEvent to Falseif __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
Copy the code

The focus of control

By default, you can switch focus with the mouse and TAB

# TabFocus can only be used with the Tab key # ClickFocus can only be used with the mouse # StrongFocus can be used with either of the above # NoFocus can not be used with either of the above Led2.setfocuspolicy (qt.clickFocus) led2.setFocus() # set a focusCopy the code

For qT5 various control summary, I will use the interface tools to design a learning and viewing tools, has completed a part, as follows

Thank you for your support!

—– is a test rookie, understanding is not in place, please forgive me.