Reputation:
I am new to QT. I started creating a TODO app and I want to somehow connect my PushButtons that are placed in vector with CheckBoxes that are also placed in a different vector.
std::vector <QPushButton*> buttons;
std::vector <QCheckBox*> checks;
I thought that the best way to do that will be to make a for loop connecting every element of mentioned vectors
Something like:
for(int i=0; i<buttons.size(); ++i){
connect(buttons[i], SIGNAL(???), checks[i], SLOT(???));
}
But idea is the only thing that I have. I tried putting different things into SIGNAL() and SLOT() but none of them worked. By "none of them worked" I mean the fact that when button is clicked nothing happens. Program is normally compiled without any error.
Upvotes: 0
Views: 1182
Reputation: 98485
Works for me - and you can store the widgets directly in a std::list
: that avoids the need to mess with manual memory management. Let the libraries do it for you.
#include <QtWidgets>
#include <list>
int main(int argc, char **argv) {
QApplication app{argc, argv};
QWidget win;
QGridLayout layout{&win};
std::list<QPushButton> buttons;
std::list<QCheckBox> checkboxes;
QPushButton addButton{"Add"};
layout.addWidget(&addButton, 0, 0, 2, 1);
auto const clicked = &QAbstractButton::clicked;
auto const toggle = &QAbstractButton::toggle;
auto const add = [&,clicked,toggle]{
int const col = layout.columnCount();
auto const text = QString::number(col);
auto *button = &(buttons.emplace_back(text), buttons.back()); //C++11, not 14
auto *checkbox = &(checkboxes.emplace_back(text), checkboxes.back());
layout.addWidget(button, 0, col);
layout.addWidget(checkbox, 1, col);
QObject::connect(button, clicked, checkbox, toggle);
};
add();
QObject::connect(&addButton, clicked, add);
win.show();
return app.exec();
}
Upvotes: 1
Reputation: 311
What about just clicked(bool)
for SIGNAL
and toggle()
for SLOT
?
Something like that:
connect(pushButton, SIGNAL(clicked(bool)), checkBox, SLOT(toggle()));
Upvotes: 2
Reputation: 28679
With Qt-5 you can now use lambda functions as slots (see connect version 5)
You can also do away with the need for the SIGNAL
macro, and instead use member function pointers.
QObject::connect(buttons[i], &QPushButton::clicked, [=]
{
// toggle the check state
checks[i]->setChecked(!checks[i]->isChecked());
});
The first two parameters are a pointer to an object, and a member function pointer
buttons[i]
is of type QPushButton*
&QPushButton::clicked
is a member function pointer of the signal you want to connect toThe second parameter is a C++11 lambda, which captures checked
and i
by value, and then sets the QCheckBox
checked state to the inverse of its previous value
Upvotes: 0