PyQt6 click events

created at 05-12-2021 views: 8

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):
        self.setWindowTitle("PyQt6 Learning")
        # call the button method

    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()

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

def clicked_btn(self):
    # change font color to white

now rerun the script and click on the button:

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

created at:05-12-2021
edited at: 05-13-2021: