tags:

views:

175

answers:

3

I have a simple QT application with 10 radio buttons with names radio_1 through radio_10. It is a ui called Selector, and is part of a class called TimeSelector

In my header file for this design, i have this:

//! [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]

the commented out void_on_inputSpinBox1_valueChanged(int value) is from the tutorial for the simple calculator. I know i can do:

void on_radio_1_valueChanged(int value);

but I would need 10 functions. I want to be able to make one function that works for everything, and lets me pass in maybe a name of the radio button that called it, or a reference to the radio button so i can work with it and determine who it was.

I am very new to QT but this seems like it should be very basic and doable, thanks.

A: 

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

void CheckWithReference(YourRadioButtonClass* rb);

or

void CheckWithReference(QString RadioButtonName);

or anything you would like to have.

Then create a slot in your TimeSelector class with the same set of parameters you will connect to all signals.

Patrice Bernassola
While this approach would work, I don't recommend it for a Qt beginner.
Lohrun
+2  A: 

You can create a unique slot and obtain the object that emitted the signal with the QObject::sender() method. The following code presents an example of such 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() will not give you a good result unless you define it explicitly somewhere.

Now, you can connect the toggled(bool checked) signal of every QRadioButton to the onRadioToggled slot. Note that QRadioButton does not have any valueChanged signal so your code cannot actually 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)));
Lohrun
+1  A: 

In the radiobutton case, add the buttons to a QButtonGroup. Similar functionality offers QSignalMapper.

Frank