In this PyQt6 lesson we are going to learn about PyQt6 Signal And Slots, Signal and Slots are used for communication between some objects. a Signal is emitted when a particular event occurs, and a Slot is called when its connected signal is emitted.
We are going to use our previous code from creating button and label in PyQt6, and we want to add some functionality for that, for example by clicking the button i want to change the text and the background color of the label.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
from PyQt6.QtWidgets import QApplication, QWidget, \ QPushButton, QLabel from PyQt6.QtGui import QIcon, QFont import sys class Window(QWidget): def __init__(self): super().__init__() self.setWindowTitle("PyQt6 Signal And Slots - Geekscoders.com") self.setWindowIcon(QIcon("qt.png")) self.setGeometry(500,200, 500,400) self.create_widgets() def create_widgets(self): btn = QPushButton("Click Me", self) #btn.move(100,100) btn.setGeometry(100,100, 100,100) btn.setStyleSheet('background-color:red') btn.setIcon(QIcon("football.png")) btn.clicked.connect(self.clicked_btn) self.label = QLabel("My Label", self) #self.label.move(100,220) self.label.setGeometry(100,220, 200,100) self.label.setStyleSheet('color:green') self.label.setFont(QFont("Times New Roman", 15)) def clicked_btn(self): self.label.setText("Text is Changed") self.label.setStyleSheet('background-color:red') app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec()) |
This is our method, and in this method we want to change the text of the label, also we want to change the background color of the label.
1 2 3 |
def clicked_btn(self): self.label.setText("Text is Changed") self.label.setStyleSheet('background-color:red') |
And now we need to connect this method with the clicked signal of the QPushButton, there are different built in signals that you can use in PyQt6, in here we want to use the clicked signal, and you can use connect method for the connection with our method.
1 |
btn.clicked.connect(self.clicked_btn) |
Run the complete code and click on the button this will be the result.
