How to use Signals & Slots
Signals & Slots is a mechanism in Qt for communication between objects. It allows you to connect signals emitted by one object to slots in another object, enabling them to communicate with each other.
Creating Signals
To use Signals & Slots, you first need to create signals in your object. Signals are similar to functions, but they do not have a body and are declared using the signals:
keyword.
class MyClass : public QObject
{
Q_OBJECT
signals:
void mySignal();
};
Creating Slots
Slots are functions that can be connected to signals. They are declared using the slots:
keyword and can be any normal member function.
class AnotherClass : public QObject
{
Q_OBJECT
public slots:
void mySlot()
{
// Do something when the signal is emitted
}
};
Connecting Signals to Slots
To connect a signal to a slot, you can use the QObject::connect
function. When the signal is emitted, the connected slot will be called.
MyClass* obj1 = new MyClass();
AnotherClass* obj2 = new AnotherClass();
QObject::connect(obj1, SIGNAL(mySignal()), obj2, SLOT(mySlot()));
Emitting Signals
To emit a signal, use the emit
keyword followed by the signal name and any arguments the signal may have.
class MyClass : public QObject
{
Q_OBJECT
signals:
void mySignal(int value);
};
void MyClass::someFunction()
{
// Emit the signal with a value
emit mySignal(42);
}
Conclusion
Signals & Slots is a powerful mechanism in Qt that allows for easy communication between objects. By creating signals in one object and connecting them to slots in another, you can enable seamless communication and interaction between different parts of your application.
Great video. Only thing is it's too small to read. If you can make the text larger it would really help. Thanks
plz Sir zoooooooom plz, thank you for this video.
Qt has literally no (updated) training videos. Other frameworks are catching up and the youngsters dont want to learn an outdated Qt with no free training videos. So easy to make as you have all the resources 😅
Memory leak. Sender and receiver objects didn't get parents. However they were allocated on a heap.
I hate cmake..qmake is so much comfortable ,intuitive,easy I am using it even for not qt projects…so why ???:(
Crystal clear, Sir. Thank you.
Now we need an updated Model View Tutorial.
Model in C++, that reads from a, say, .json file, and the rest in QML.