2019-01-23

QT Signals Slots


Signals and slots are like direct links. It's an event system where a signal will pass its arguments to the connected slot. It's similar to python and probably the most peculiar feature of QT.

The Signal slots paradigm makes GUI desing a lot simpler. Something happens->do something else. They are also thread safe for good measure.

Internally QT will translate signals slots and connect in real C++ code in meta C++ files before the real compilation begins.

Here I added a slot to the main class. It's a public method with a macro definition used by QT for his translation into real C++ code.

class MainWindow : public QMainWindow
{
    Q_OBJECT

    public:
        explicit MainWindow(QWidget *parent = nullptr);
        ~MainWindow();

    public Q_SLOTS:
        void txt_update( int num );

    private:
        Ui::MainWindow *ui;
};




The slots take care of writing an integer inside a line control

void MainWindow::txt_update( int num )
{
    User::Qt_utils::qline_show_int( ui ->txt, num );
}
I have an object with a signal. The signal too is public and declared as macro.


class Sender : public QObject
{
    Q_OBJECT

    public:
        Sender();

    Q_SIGNALS:
        void send( int num );
};
Here is the code inside the constructor of the main window.
I create the sender object.
I call directly the slot to update the control and initialize it.
I connect the sender output with the slot input.
I call the sender object which will pass it's argument to the slot automagically!
//I can call a slot directly //This slot is set to update the txt control wint an integer when called this -> txt_update( 0 ); //QT will actually add more c++ files to handle signals and slots in real C++ code //Connect the signal coming from the sender class to the slot of the Main Window class //singal and slot must have same arguments in this style of connect connect ( &my_tx, //Reference to source signal object &Sender::send, //Reference to the source signal method. It's just the definition and it's not tied to the individual object. this, //Reference to the dest slot object. In this case I use the current class instance &MainWindow::txt_update //Reference to the dest slot method. It's just the definition and it's not tied to the individual object. ); //I can send a signal by simply calling the method directly //This will cause the slot of the main class to be activated with the same argument of the sender signal my_tx.send( 17 );

No comments: