[solved] foreach (QPushButton, QVBoxLayout) question ?
-
wrote on 13 Mar 2014, 09:33 last edited by
The following code adds Pushbuttons to QVBoxLayout:
@void MainWindow::on_pb_test_1_clicked() {vlw_1 = new QWidget(this); vlw_1->setObjectName(QString::fromUtf8("vlW_1")); vlw_1->setGeometry(QRect(10, 10, 40, 200)); vl_1 = new QVBoxLayout(vlw_1); vl_1->setSpacing(6); vl_1->setContentsMargins(11, 11, 11, 11); vl_1->setObjectName(QString::fromUtf8("vl_1")); vl_1->setContentsMargins(0, 0, 0, 0); for (int i=0; i<5;i++) { pb_x = new QPushButton(vlw_1); pb_x->setObjectName(QString("pb_x%1").arg(i)); pb_x->setText(QString("x%1").arg(i)); pb_x->setCheckable(true); vl_1->addWidget(pb_x); } vlw_1->setStyleSheet("QPushButton:checked{color: green; background-color: red;}"); vlw_1->show();
}@
in another function i want to access all this Pushbuttons in this QVBoxLayout using 'foreach'
@void MainWindow::on_pb_test_2_clicked() {
qDebug() << vl_1->count(); qDebug() << vlw_1->children().count(); foreach(QPushButton *x, ??? ) { // do something on each Pushbutton }@
By what should be "???" substituted ?
-
Nothing: it will not work with QLayout.
But you can use "QObject::findChildren()":http://qt-project.org/doc/qt-5/qobject.html#findChildren to get all QPushButtons and iterate over the list that is returned.
-
wrote on 13 Mar 2014, 13:02 last edited by
@void MainWindow::on_pb_test_2_clicked() {
QList<QPushButton*> bList = vlw_1->findChildren<QPushButton*>(); foreach(QPushButton *x, bList) { qDebug() << x->objectName() ; }
}@
works nice on the QWidget vlw_1. Maybe my fist foreach approach works on QWidget ? -
"foreach" works on container classes, that is:
- QList
- QStringList
- QMap
- QHash
- QVector
- probably some more (QQueue, QMultiHash, etc.)
it does not work on QWidget or QLayout by itself. But when you have - for example - a list of widgets, then it is a different story (and a happy one: see the solution that works for you :)).
1/4