E2 - signals, slots and events

signals and slots

signals

  • notifications sent out by widgets when something happens

slots

  • they are the receivers of signals

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        
        self.button_is_checked = True ## to store the button status

        self.setWindowTitle("My App")
        
        button = QPushButton("Press Me!")
        button.setCheckable(True)
        button.clicked.connect(self.the_button_was_clicked)
        button.setChecked(self.button_is_checked)
        
        self.setCentralWidget(button)

    def the_button_was_clicked(self):
	    self.button_is_checked = True
    
        print("Clicked!")


app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec()

changing the interface

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()

        self.setWindowTitle("My App")

        self.button = QPushButton("Press Me!")
        self.button.clicked.connect(self.the_button_was_clicked)
        
        self.setCentralWidget(self.button)
           

    def the_button_was_clicked(self):
        self.button.setText("You already clicked me.")
        self.button.setEnabled(False)

        self.setWindowTitle("New App")

connecting widgets together directly

from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QVBoxLayout, QWidget

import sys


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle('my app')

        self.label = QLabel()

        self.input = QLineEdit()
        self.input.textChanged.connect(self.label.setText)

        layout = QVBoxLayout()
        layout.addWidget(self.input)
        layout.addWidget(self.label)
        
        container = QWidget()
        container.setLayout(layout)

        self.setCentralWidget(container)


app = QApplication(sys.argv)

window = MainWindow()
window.show()


app.exec()

events

events

  • any interaction the user has with a Qt application

event handler event type moved
mouseMoveEvent mouse moved
mousePressEvent mouse button pressed
mouseReleaseEvent mouse button released
mouseDoubleClickEvent double click detected