Search code examples
c++qtsignals

How QT signals with parameters works


can someone tell me how exactly signals with parameters work? I mean... if i have declared signal f.e.:

void sign1(int)

how should i specify what integer i want to send with that signal? Also, can i declare signal with multiple arguments? Like:

void sign2(int, int)

And again... i want to send with sign2 two out of four variables that i have. Is that possible, and how it should be done? To specify my question below is a little more detailed example:

class Board
{
  signals: 
    void clicked(int, int);
  private:
    int x1{4}; int x2{4}; int x3{5}; int x4{8};
}

and there is board.ui file with pushbutton. After pushbutton is clicked i want to send to the slot for example x1 and x3. Example:

connect(ui->button, SIGNAL(clicked(int, int)), obj2, slot2); 

I hope that it's somehow clear. I will really appreciate your help.


Solution

  • QObject::connect() works like this (in the general case, not using lambda):

    connect(obj1, obj1_signal, obj2, ob2_slot)
    

    Since there is no signal clicked(int, int) in the class QPushButton (which I assume you are using), it cannot be use for the connection.

    If you want to have the signal clicked(int, int) in a button, you can subclass QPushButton, add the signal, and using emit to send the signal where the click event is handled.

    However, that is not a good design, since you will have to store a Board object (or at least a reference to it) in the button class, which is irrelevant to the class.
    Instead, you can have a slot Board::buttonClicked(), connected to QPushButton::clicked(bool). Then in that slot, you can do emit Board::clicked(int, int).