Signals and Slots Fundamentals
Signals and slots form Qt's event-driven communication system between objects:
- Signals: Events emitted by objects (e.g., button click notification)
- Slots: Receiver functions that respond to signals (e.g., light activation method)
- Connections: Links signals to slots using
QObject::connect()
Connection Syntax
// Modern Qt5+ syntax
QObject::connect(transmitter, &TransmitterClass::signalEvent,
receiver, &ReceiverClass::responseMethod);
// Example implementation
LightSwitch* switch = new LightSwitch;
LightBulb* bulb = new LightBulb;
connect(switch, &LightSwitch::activated,
bulb, &LightBulb::illuminate);
Connnection rules:
- Slot parameters must match signal parameters (type and order)
- Slots may have fewer parameters than signals
- Objects must inherit from QObject
Automatic Connection Generation
Qt Creator generates slot functions using naming conventions:
// Auto-generated slot for triggerButton click
void MainUI::on_triggerButton_clicked() {
setWindowTitle("Operation Activated");
}
Naming pattern: on_<objectName>_<signal>
Custom Signals and Slots
class Sensor : public QObject {
Q_OBJECT
public slots:
void recordMeasurement(double value); // Custom slot
signals:
void dataReady(QByteArray dataset); // Custom signal
};
// Connection example
connect(sensorA, &Sensor::dataReady,
logger, &Logger::recordMeasurement);
Implementation requirements:
- Signals:
voidreturn type, declaration only - Slots:
voidreturn type, full implementasion
Connection Management
Disconnect established links:
// Disconnect specific connection
disconnect(transmitter, &TransmitterClass::signalEvent,
receiver, &ReceiverClass::responseMethod);
// Disconnect all receiver connections
disconnect(receiver, nullptr, nullptr, nullptr);
Lambda Expressions as Slots
QPushButton* configBtn = new QPushButton("Configure");
connect(configBtn, &QPushButton::clicked, [=](){
qDebug() << "Configuration requested at" << QTime::currentTime();
applySettings();
});
Advantages and Limitations
Benefits:
- Type-safe communication
- Decoupled object interactions
- Thread-aware connections
- Support for lambda expressions
Constraints:
- Performance overhead vs direct calls
- Debugging complexity
- Requires QObject inheritance
- Slot paramter limitations