Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an array of custom buttons. I want to create a custom signal, which, when connected to a slot, which takes an integer as an argument, will send a variable to it.
So for example, let's say I've got 10 buttons, each of them has an id from 0 to 9. I connect all of them to a single function, which takes an integer argument. The function, when called, prints it's argument. Now when I press button 4, I want to see a 4 printed on my screen.

I've never created a custom signal before, so I'd be very grateful for any help.

What I have tried:

I haven't tried anything yet. I've only created the class.
Posted
Updated 27-Aug-18 1:47am
v3
Comments
Richard MacCutchan 26-Aug-18 11:29am    
You have 10 buttons each of which has an id. So when your function gets called you just need to identify which button called it. I don't know how this works in Qt, in C# the button id would be sent to the function.

1 solution

Just implement a QPushButton::clicked() slot that is connected to multiple push buttons. Inside that cast sender() to QPushButton* to access the button and identify it. You can then emit a user defined signal with additional parameters.

Another method would be using a C++11 lambda:
C++
int counter = 1;

// Create button or access it using the ui member 
//QPushButton *button = new QPushButton;

button->setProperty("myId", counter++);
connect(button, &QPushButton::clicked, [this, button](){
    qDebug() << button->property("myId").toString();
    ui->label->setText(button->text());
});

// Repeat for the other buttons
The above is using the property system to provide IDs, printing it to the debug window and setting a label to the button's caption text.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900