Search code examples
c++qtuser-interfaceiteratorsignals-slots

Use connect, signals and slots by iterator


I'm trying to build a GUI with a lot of buttons to be connected to one slot. I therefore would like to add them into a vector and then connect all of these by an iterator.

Example:

std::vector<QRadioButton*> buttonVec;
buttonVec.push_back(ui->radioA);
buttonVec.push_back(ui->radioB);
buttonVec.push_back(ui->radioC);
//...
for(std::vector<QRadioButton*>::iterator it = buttonVec.begin(); it != buttonVec.end(), it++)
    connect(*it, SIGNAL(released()), this, SLOT(handleRadioVec()));
//...

Unfortunately, this leads to an error during runtime (not building), where the same connect-code line but with the direct objects runs without any problems:

QObject::connect: Cannot connect (null)::released() to MainWindow::handleRadioVec()

Anyone knows why?


Solution

  • You're using ui, which I assume means your widgets are set up using the UIC compiler. Bear in mind that you have to actually create the widgets (by calling setupUi) before you can use them. Until then, ui->anything will be null pointers.

    So call setupUi(this) before you fill buttonVec.