Signals and Slots

COS2614 - Programming: Contemporary Concepts · Qt Framework Basics

Signals and Slots in Qt

In Qt, signals and slots are a key feature that enables communication between objects. This mechanism allows objects to send notifications to each other when certain events occur. The signal is emitted when a particular event happens, while the slot is a function that is called in response to the signal.

Understanding Signals

A signal is emitted when a specific action occurs. For example, when a user clicks a button, the button emits a signal. Signals do not require a receiver to be connected to them; they can exist independently.

Remember: Signals are defined in the class where the event occurs and are usually declared in the public section.

Understanding Slots

A slot is a function that is called in response to a particular signal. Slots can be defined in any class and can respond to signals from different objects. Slots can also have parameters, which can be used to pass data when the signal is emitted.

Connecting Signals and Slots

To connect a signal to a slot, you use the QObject::connect() method. The syntax is as follows:

QObject::connect(sender, SIGNAL(signalName()), receiver, SLOT(slotName()));

Here, sender is the object that emits the signal, receiver is the object that contains the slot, signalName() is the name of the signal, and slotName() is the name of the slot.

Example of Signals and Slots

Consider the following example where we create a simple GUI application that calculates the Body Mass Index (BMI) based on user input. In this example, we will connect a button click signal to a slot that performs the BMI calculation.

#include <QApplication>
#include <QPushButton>
#include <QMessageBox>
#include <QDoubleSpinBox>
#include <QVBoxLayout>
#include <QWidget>

class BMICalculator : public QWidget {
    Q_OBJECT

public:
    BMICalculator() {
        QPushButton *calculateButton = new QPushButton("Calculate BMI");
        QDoubleSpinBox *weightInput = new QDoubleSpinBox();
        QDoubleSpinBox *heightInput = new QDoubleSpinBox();

        QVBoxLayout *layout = new QVBoxLayout;
        layout->addWidget(weightInput);
        layout->addWidget(heightInput);
        layout->addWidget(calculateButton);
        setLayout(layout);

        connect(calculateButton, SIGNAL(clicked()), this, SLOT(calculateBMI()));
    }

public slots:
    void calculateBMI() {
        double weight = weightInput->value();
        double height = heightInput->value();
        double bmi = weight / (height * height);
        QMessageBox::information(this, "BMI Result", QString("Your BMI is: %1").arg(bmi));
    }
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    BMICalculator calculator;
    calculator.show();
    return app.exec();
}

In this example, when the user clicks the "Calculate BMI" button, the clicked() signal is emitted. This signal is connected to the calculateBMI() slot, which performs the calculation and displays the result in a message box.

Using Lambda Functions with Signals and Slots

Qt also allows you to connect signals to lambda functions. This feature provides a more flexible way to handle signals without needing to create a separate slot in the class. Here is an example:

QObject::connect(calculateButton, &QPushButton::clicked, [&]() {
    double weight = weightInput->value();
    double height = heightInput->value();
    double bmi = weight / (height * height);
    QMessageBox::information(this, "BMI Result", QString("Your BMI is: %1").arg(bmi));
});

This approach simplifies the code and keeps related logic together.

Watch Out for Common Mistakes

Watch out: Ensure that the signal and slot signatures match. If they do not, the connection will not work, and you may not receive any error messages.

Practical Application

Understanding signals and slots is crucial for building responsive applications in Qt. You will frequently use this mechanism in your projects, whether for button clicks, menu selections, or other user interactions. Practice by creating small applications that use signals and slots to get comfortable with the concept.

Check Your Understanding

  • What is the purpose of signals in Qt?
  • How do you connect a signal to a slot?
  • What happens if the signal and slot signatures do not match?
  • Provide an example of using a lambda function with signals and slots.

Test yourself

5 quick questions on this lesson. Pick an answer to see if you're right.

  1. 1. How can you use a lambda function with signals and slots in Qt?

  2. 2. What is a slot in the context of Qt's signals and slots?

  3. 3. Where are signals typically declared in a Qt class?

  4. 4. What is the role of a signal in the Qt framework?

  5. 5. Why is it important to understand signals and slots in Qt programming?