Connecting signal and slot¶
Let’s create a program that displays the values adjusted with the dial widget on the screen.
Signals that occur when the value of the dial changes are connected to slots that display numbers on the LCD screen.
Example¶
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLCDNumber, QDial, QVBoxLayout
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
lcd = QLCDNumber(self)
dial = QDial(self)
vbox = QVBoxLayout()
vbox.addWidget(lcd)
vbox.addWidget(dial)
self.setLayout(vbox)
dial.valueChanged.connect(lcd.display)
self.setWindowTitle('Signal and Slot')
self.setGeometry(300, 300, 200, 200)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
When you rotate the dial, the LCD displays numbers according to the value.
Description¶
lcd = QLCDNumber(self)
dial = QDial(self)
The QLCDNumber widget displays numbers like LCD screens. QDial is a widget that rotates the dial to adjust its value.
vbox = QVBoxLayout()
vbox.addWidget(lcd)
vbox.addWidget(dial)
self.setLayout(vbox)
Create a vertical box layout (see the box layout page) to include the QLCDNumber and QDial widgets. Then set it as the layout of the MyApp widget.
dial.valueChanged.connect(lcd.display)
The QDial widget has several signals. (see the QSlider, QDial page)
Here you connect the valueChanged signal to the display slot on the lcd. The display slot takes the number and displays it on the QLCDNumber widget.
Here the dial is the sender of the signal and the lcd is the receiver of the signal. Slot is a method that embodies how to react to a signal.