python - 如何使用 for 循环访问 PyQt 中多个复选框的复选框文本?
问题描述
我想访问多个复选框的复选框文本,例如。self.checkBox_x.setText("Hello World")
其中 x 等于 1 到 100。是否有可能在任何循环的帮助下打印出来。复选框的 objectName 编号checkBox_1
为checkBox_100
。
解决方案
您可以使用setattr()
/getattr()
来动态创建变量。
import sys
from PyQt5.Qt import *
class Example(QWidget):
def __init__(self):
super().__init__()
lay = QVBoxLayout(self)
for i in range(10):
self.checkBox = QCheckBox(f'cb_{i+1}')
lay.addWidget(self.checkBox)
setattr(self, "checkBox_{}".format(i+1), self.checkBox)
lay.addWidget(QPushButton("Click me", clicked=self.create_txt))
def create_txt(self):
for i in range(10):
obj = getattr(self, "checkBox_{}".format(i+1))
obj.setText("Hello World")
if __name__ == "__main__":
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())
推荐阅读
- asynchronous - useEffect() 导致 api 调用无限循环
- fork - Socat DTLS fork - 过度创建进程
- visual-studio - 获取 Flutter APK 文件
- python - 如何解决酸洗阿拉伯语文本问题?
- reactjs - 为 2 列的列表设置样式
- c++ - 如何通过可变参数传递给另一个函数?
- javascript - 无论如何,使用 Ajax 调用的 JS 脚本都会保留在缓存中
- javascript - JSON.stringify document.getSelection() 对象
- docker - Flutter web:在更改 web 版本和禁用 nginx 缓存策略后保持缓存
- nlp - huggingface 的 ReformerForMaskedLM 配置问题