首页 > 解决方案 > 如何使用 for 循环访问 PyQt 中多个复选框的复选框文本?

问题描述

我想访问多个复选框的复选框文本,例如。self.checkBox_x.setText("Hello World")其中 x 等于 1 到 100。是否有可能在任何循环的帮助下打印出来。复选框的 objectName 编号checkBox_1checkBox_100

标签: pythonpyqt5

解决方案


您可以使用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_())

在此处输入图像描述


推荐阅读