Analysis of pyqt5 custom signal instances and pyqt5 custom instances

Source: Internet
Author: User
Tags qt designer

Analysis of pyqt5 custom signal instances and pyqt5 custom instances

This article focuses on the analysis of pyqt5 custom signal instances.

PyQt5 has automatically defined many built-in QT signals. However, in actual use, in order to flexibly use the signal and slot mechanism, we can customize signal as needed. You can use the pyqtSignal () method to define new signals. New signals are used as class attributes.

Description of custom signal:

PyqtSignal () method prototype (defined on the PyQt official website ):

PyQt5.QtCore. pyqtSignal (types [, name [, revision = 0 [, arguments = [])
Create one or more overloaded unbound signals as a class attribute.

Parameters:
Types-the types that define the C ++ signature of the signal. each type may be a Python type object or a string that is the name of a C ++ type. alternatively each may be a sequence of type arguments. in this case each sequence defines the signature of a different signal overload. the first overload will be the default.

Name-the name of the signal. If it is omitted then the name of the class attribute is used. This may only be given as a keyword argument.

Revision-the revision of the signal that is exported to QML. This may only be given as a keyword argument.

Arguments-the sequence of the names of the signal's arguments that is exported to QML. This may only be given as a keyword argument.
Return type: an unbound signal

The new signal should be defined in the subclass of QObject. The new signal must be part of the definition class and cannot be added dynamically after the class definition as the class property. In this way, new signals can be automatically added to the QMetaObject class. This means that the new defined signal will appear in Qt Designer and can be saved through the QMetaObject API.

The following example shows the definition of signal:

From PyQt5.QtCore import QObject, pyqtSignalclass NewSignal (QObject): # defines a "closed" signal. This signal has no parameter. According to closed = pyqtSignal () # defines a "range_changed" signal, this signal has two int type parameters: range_changed = pyqtSignal (int, int, name = 'rangechanged ')

The launch of custom signals is implemented through the emit () method class. For details, see the prototype of this function:

Emit (* args)
Parameters: args-the optional sequence of arguments to pass to any connected slots.

The following example shows how to use emit:

From PyQt5.QtCore import QObject, pyqtSignalclass NewSignal (QObject): # A valueChanged signal, which has no parameters. valueChanged = pyqtSignal () def connect_and_emit_valueChanged (self): # bind the signal and slot function self. valueChanged. connect (self. handle_valueChanged) # transmit signal. self. trigger. emit () def handle_valueChanged (self): print ("trigger signal pinned ed ")
Example:

The general process of custom signals is as follows:

1. Define the signal
2. Define slot Functions
3. Bind signals and slots
4. Transmit signals

Use the sample code to understand the custom process of the signal:

#-*-Coding: UTF-8-*-''' defined Signal ''' _ author _ = 'Tony zhu' import sysfrom PyQt5.QtCore import pyqtSignal, QObject, Qt, pyqtSlotfrom consumer import QWidget, QApplication, QGroupBox, metrics, QLabel, QCheckBox, QSpinBox, metrics, QComboBox, metrics SignalEmit (QWidget): helpSignal = pyqtSignal (str) printSignal = pyqtSignal) # declare a multi-Load version signal, including a signal with int and str parameters, and a signal with str parameters previewSignal = pyqtSignal ([int, str], [str]) def _ init _ (self): super (). _ init _ () self. initUI () def initUI (self): self. creatContorls ("print control:") self. creatResult ("Operation Result:") layout = QHBoxLayout () layout. addWidget (self. controlsGroup) layout. addWidget (self. resultGroup) self. setLayout (layout) self. helpSignal. connect (self. showHelpMessage) self. printSignal. connect (self. printPaper) self. previewSignal [str]. connect (self. previewPaper) self. previewSignal [int, str]. connect (self. previewPaperWithArgs) self. printButton. clicked. connect (self. emitPrintSignal) self. previewButton. clicked. connect (self. emitPreviewSignal) self. setGeometry (300,300,290,150) self. setWindowTitle ('defined signal ') self. show () def creatContorls (self, title): self. controlsGroup = QGroupBox (title) self. printButton = QPushButton ("print") self. previewButton = QPushButton ("preview") numberLabel = QLabel ("Print count:") pageLabel = QLabel ("paper type:") self. previewStatus = QCheckBox ("full screen preview") self. numberSpinBox = QSpinBox () self. numberSpinBox. setRange (1,100) self. styleCombo = QComboBox (self) self. styleCombo. addItem ("A4") self. styleCombo. addItem ("A5") controlsLayout = QGridLayout () controlsLayout. addWidget (numberLabel, 0, 0) controlsLayout. addWidget (self. numberSpinBox, 0, 1) controlsLayout. addWidget (pageLabel, 0, 2) controlsLayout. addWidget (self. styleCombo, 0, 3) controlsLayout. addWidget (self. printButton, 0, 4) controlsLayout. addWidget (self. previewStatus, 3, 0) controlsLayout. addWidget (self. previewButton, 3, 1) self. controlsGroup. setLayout (controlsLayout) def creatResult (self, title): self. resultGroup = QGroupBox (title) self. resultLabel = QLabel ("") layout = QHBoxLayout () layout. addWidget (self. resultLabel) self. resultGroup. setLayout (layout) def emitPreviewSignal (self): if self. previewStatus. isChecked () = True: self. previewSignal [int, str]. emit( 1080, "Full Screen") elif self. previewStatus. isChecked () = False: self. previewSignal [str]. emit ("Preview") def emitPrintSignal (self): pList = [] pList. append (self. numberSpinBox. value () pList. append (self. styleCombo. currentText () self. printSignal. emit (pList) def printPaper (self, list): self. resultLabel. setText ("Print:" + "Number of copies:" + str (list [0]) + "paper:" + str (list [1]) def previewPaperWithArgs (self, style, text): self. resultLabel. setText (str (style) + text) def previewPaper (self, text): self. resultLabel. setText (text) def keyPressEvent (self, event): if event. key () = Qt. key_F1: self. helpSignal. emit ("help message") def showHelpMessage (self, message): self. resultLabel. setText (message) # self. statusBar (). showMessage (message) if _ name _ = '_ main _': app = QApplication (sys. argv) dispatch = SignalEmit () sys.exit(app.exe c _())

After running this function, the effect is as follows:

Example:

You can use a simulated printing interface to describe in detail about the custom signal. When printing, you can set the print score and paper type. After the "print" button is triggered, display the execution result to the right. Use full screen preview QCheckBox to select whether to preview in full screen mode and display the execution result to the right.
Click the F1 shortcut key to display helpMessage information.

Code Analysis:

L12 ~ 15:

HelpSignal = pyqtSignal (str) printSignal = pyqtSignal (list) # declare a signal of multiple overloaded versions, including a signal with int and str parameters, and the signal previewSignal = pyqtSignal ([int, str], [str]) with the str Parameter

Three signals, helpSignal, printSignal, and previewSignal, are defined using pyqtSignal. Where:

HelpSignal is a signal of the str parameter type;

PrintSignal is a signal of the list parameter type;

PreviewSignal is a signal of multiple overloaded versions, including a signal with int and str parameters and parameters of str-type lines.

self.helpSignal.connect(self.showHelpMessage)self.printSignal.connect(self.printPaper)self.previewSignal[str].connect(self.previewPaper)    self.previewSignal[int,str].connect(self.previewPaperWithArgs)     self.printButton.clicked.connect(self.emitPrintSignal)    self.previewButton.clicked.connect(self.emitPreviewSignal)

Bind signals and slots. This section focuses on the signal binding of multiple overloaded versions. previewSignal has two versions: previewSignal (str) and previewSignal (int, str ). Because there are two versions, you need to explicitly specify the binding relationship between the signal and the slot when binding.

The details are as follows:

Self. previewSignal [str]. connect (self. previewPaper) self. previewSignal [int, str]. connect (self. previewPaperWithArgs)

The previewSignal signal of the [str] parameter is bound to previewPaper (); The previewSignal signal of [int, str] is bound to previewPaperWithArgs ()

L72 ~ 76:

  def emitPreviewSignal(self):    if self.previewStatus.isChecked() == True:      self.previewSignal[int,str].emit(1080," Full Screen")    elif self.previewStatus.isChecked() == False:      self.previewSignal[str].emit("Preview")

The launch version of signals of multiple overloaded versions also needs to be developed, similar to the same signal version.

L78 ~ 82:

  def emitPrintSignal(self):    pList = []    pList.append(self.numberSpinBox.value ())    pList.append(self.styleCombo.currentText())    self.printSignal.emit(pList)

As shown in the code, python data parameters can be passed during signal transmission, and list parameters pList can be passed in this example.

L93 ~ 96:

  def keyPressEvent(self, event):    if event.key() == Qt.Key_F1:      self.helpSignal.emit("help message")

The F1 shortcut key is expanded using the rewrite keyPressEvent () method. In most windows applications, some shortcut keys are used to quickly complete certain functions. For example, the F1 key will quickly bring up the help interface. Then we can re-write the keyPressEvent () method to simulate the desired signal to complete our corresponding task.

Note:

1. The custom signal is defined before the init () function;
2. Custom model parameters can be passed, such as str, int, list, object, float, tuple, and dict;
3. Pay attention to the call logic of signal and slot to avoid endless loops between signal and slot. If the slot method continues to emit the signal;

Summary

The above is all the content about parsing the pyqt5 custom signal instance. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.