QT/C++通过从变量中获取QObject的名称来设置其属性

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

本文关键字:设置 属性 QObject 获取 C++ 变量 QT      更新时间:2023-10-16

我有一堆lineEdits,命名为"e1"、"e2"、"e3"等等。我想在一个循环中为所有这些设置相同的样式表,而不是对这个进行编码

    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");

但是像这样的东西:

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

也许还有另一种方法可以为一堆类似的对象设置属性?感谢您的帮助,提前感谢!

有几种方法可以做到这一点。

阵列

如果你正在使用Qt设计器,这将是一件很痛苦的事情。但如果不是,只需将你所有的QLineEdit塞到std::array中,然后从那里开始。

命名约定

QLineEdit强制执行顺序命名约定,例如infoField1infoField2等。然后只需调用some_qobject.findChild(QString("infoField%1").arg(i))。然而,这很容易出错。

样式表

我实际上还没有在Qt中使用样式表,但看起来你在使用类似CSS的东西,对吧?在这种情况下,难道你不应该只写一种风格并将其应用于一组特定的(甚至所有的)QLineEdit吗?我相信这将是一个寻找它的好地方。

得到了。

为此使用了findChild方法和循环。

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

工作起来很有魅力,不过要感谢@JesseTG引入动态属性