Roman Alexeev
Roman Alexeev

Reputation: 1

QT/C++ Setting attributes to QObject by getting its name from variable

i have a bunch of lineEdits named like "e1", "e2", "e3" and so on. i'd like to set same Style Sheet to all of them in a loop, not to code this

    ui->e1->setStyleSheet("background-color: white");    
    ui->e2->setStyleSheet("background-color: white");
    ui->e3->setStyleSheet("background-color: white");
    ui->e4->setStyleSheet("background-color: white");
    ui->e5->setStyleSheet("background-color: white");
    ui->e6->setStyleSheet("background-color: white");

but something like this:

    for (z=1; z<7; z=z+1)
    {ui->e&z->setStyleSheet("background-color: white");}

maybe there is another way to set attributes to a bunch of similar objects? any help is appreciated, thank you in advance!

Upvotes: 0

Views: 344

Answers (2)

Roman Alexeev
Roman Alexeev

Reputation: 1

got it.

used findChild method and loop for this.

    for (int e=1; e<7; e= e+1)
    {
      QLineEdit *field = findChild<QLineEdit*>("e" +QString::number(e));
      field->setStyleSheet("background-color: white");
      field->setText("");
    }

works like a charm, nevertheless thanks @JesseTG for introduction of dynamic properties

Upvotes: 0

JesseTG
JesseTG

Reputation: 2123

There's several ways you could do this.

Arrays

If you're using the Qt Designer, this will be a pain to do. But if not, just stuff all your QLineEdits into a std::array and take it from there.

Naming Conventions

Enforce a sequential naming convention for your QLineEdits, e.g. infoField1, infoField2, etc. Then just call some_qobject.findChild(QString("infoField%1").arg(i)). This is error-prone, however.

Stylesheets

I haven't actually used stylesheets with Qt, but it looks like you're using something CSS-like with it, right? In that case, shouldn't you be able to just write one style and apply it to a particular set of (or even all) QLineEdits? I believe this would be a good place to look for that.

Upvotes: 1

Related Questions