PyQt6 click events

created at May 12, 2021, 1:19 p.m. views: 0

In this article we will implement a small function by clicking on a button.

Basic window

The snippet below is a basic window, we can run and see the window with a button and a label aside it.

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QLabel
from PyQt6.QtGui import QIcon


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyQt6 Learning")
        self.setWindowIcon(QIcon("python.png"))
        self.setStyleSheet("background-color:purple")
        # call the button method
        self.create_button_group()

    def create_button_group(self):
        # create a button
        btn = QPushButton("Click", self)
        # setting the coordinates, width and height
        btn.setGeometry(100, 100, 50, 25)
        # create a label
        label = QLabel("Button:", self)
        # setting the coordinates, width and height of label
        label.setGeometry(50, 100, 50, 25)


app = QApplication([])

window = Window()

window.show()
sys.exit(app.exec())

Click event:  changing the color of the label by clicking the button

first, we need to make a small change to the label object: adding self. to wherever “label” occurs:

...
def create_button_group(self):
        btn = QPushButton("Click", self)
        btn.setGeometry(100, 100, 50, 25)

        self.label = QLabel("Button:", self)  
        self.label.setGeometry(50, 100, 50, 25)  
...

Explanation: Since we are going to create a new method to control the color of the label, our new method need to access the label. However, the label was under the create_button_group() method like a local variable, so we make it to be one of the attributes of the __init__ method by adding a self. to the it. Or we can directly move the “label” sentences into __init__ method.

Now, we create a method to do things after the clicking: 

def create_button_group(self):
    ...
    # once clicked, the "clicked_btn" method be called
    btn.clicked.connect(self.clicked_btn) 

def clicked_btn(self):
    # change font color to white
    self.label.setStyleSheet("color:white") 

now rerun the script and click on the button:

the color of the label “Button” has been changed to white.

Please log in to leave a comment.