QT/C++通过从变量中获取QObject的名称来设置其属性
QT/C++ Setting attributes to QObject by getting its name from variable
我有一堆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
强制执行顺序命名约定,例如infoField1
、infoField2
等。然后只需调用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引入动态属性
相关文章:
- C++ 命名参数习惯用语 - 未设置字符串属性
- 如何将字符串属性设置为 QTreeWidgetItem?
- 由 JOB 中的进程启动的子进程是否可以将 JOB 属性设置为脱离作业?
- 是否可以在单独的线程中将 QObject 设置为 QML 上下文属性?
- CMake 设置使用不正确的参数数调用的目标属性
- 如何使用C++获取/设置OBS中的垂直滚动过滤器属性?
- 设置使用 Cereal 序列化库时可以在序列化函数中访问的属性
- 创建新对象并立即为其设置属性时出现编译器错误
- 重载>>运算符未在输入上设置属性
- 清除同一属性后,设置属性时拒绝访问
- 如何在不更改代码的情况下为所有C++函数设置属性
- C++到QML-设置属性
- C++派生类的设置属性到从同一基类派生的未知类对象
- 单词 CAddin - 设置属性与C++
- 从 Lua 设置 C 属性
- 仅在错误的着色器程序中设置属性会影响属性值
- 设置(属性)类的单个/多个成员的最佳做法
- 问题:何时使用继承与设置属性
- Setstylesheet没有单独设置属性
- Linux中的OpenCv videoccapture错误-不支持设置属性#0