QT NOOB: Add action handler for multiple objects of the same type

I have a simple QT application with 10 radio buttons named radio_1 through radio_10. This is a ui called Selector and is part of the TimeSelector class

In my header file for this design, I have the following:

//! [1]
class TimeSelector : public QWidget
{
    Q_OBJECT

public:
    TimeSelector(QWidget *parent = 0);

private slots:
    //void on_inputSpinBox1_valueChanged(int value);
    //void on_inputSpinBox2_valueChanged(int value);

private:
    Ui::Selector ui;
};
//! [1]

      

commented void_on_inputSpinBox1_valueChanged (int value) from the tutorial for a simple calculator. I know what I can do:

void on_radio_1_valueChanged(int value);

      

but I will need 10 functions. I want to be able to make one function that works for everything and allows me to pass perhaps the name of the switch that is calling it, or a reference to the switch so that I can work with it and determine who it was.

I am very new to QT but it looks like it should be very simple and doable, thanks.

+2


a source to share


3 answers


You can create a unique slot and get the object that emitted the signal using the method QObject::sender()

. The following example provides an example of such a slot:

public slots:
  void onRadioToggled(bool checked)
  {
    QRadioButton *radio = qobject_cast< QRadioButton* >(QObject::sender());
    // radio is the object that emitted the triggered signal
    // if the slot hasn't been triggered by a QRadioButton, radio would be NULL
    if (radio) {
      qDebug() << radio->objectName() << " is set to " << checked << ".";
    }
  }

      

Note that radio->objectName()

it won't give you a good result unless you explicitly define it somewhere.



Now you can connect toggled(bool checked)

each signal QRadioButton

to the slot onRadioToggled

. Please note that QRadioButton

it has no signal valueChanged

, so your code cannot work.

connect(radio_1, SIGNAL(toggled(bool)), SLOT(onRadioToggled(bool)));
connect(radio_2, SIGNAL(toggled(bool)), SLOT(onRadioToggled(bool)));
...
connect(radio_10, SIGNAL(toggled(bool)), SLOT(onRadioToggled(bool)));

      

+4


a source


In the radio case, add buttons to the QButtonGroup. Similar functionality is offered by QSignalMapper.



+1


a source


What you can do is create your own radio button class that inherits QRadioButton and creates a signal. This signal can have all the required parameters.

void CheckWithReference(YourRadioButtonClass* rb);

      

or

void CheckWithReference(QString RadioButtonName);

      

or whatever you would like to have.

Then create a slot in your class TimeSelector

with the same set of parameters that you will connect to all signals.

0


a source







All Articles