python - 是否可以通过将 lineEdit 插入 for 来缩短 PyQt5 中的代码?

标签 python pyqt5

我有 7 个 lineEdit block ,我希望在其中任何一个发生更改时触发 textChanged 函数,我决定采用简单的路线并按顺序写出它们,但现在我想缩短我的代码。

我想缩短这个

        self.lineEdit_2.textChanged.connect(self.textChanged)
        self.lineEdit_3.textChanged.connect(self.textChanged)
        self.lineEdit_4.textChanged.connect(self.textChanged)
        self.lineEdit_5.textChanged.connect(self.textChanged)
        self.lineEdit_6.textChanged.connect(self.textChanged)
        self.lineEdit_7.textChanged.connect(self.textChanged)
        self.lineEdit_8.textChanged.connect(self.textChanged)

像这样

        for n in range(2, 8):  #check changes on the all lineEdit units
            self.lineEdit_n.textChanged.connect(self.textChanged)

或者像这样

        for n in range(2, 8):
            self.lineEdit_n.textChanged.connect(self.textChanged)
            getattr(self, 'lineEdit_n%' % n).textChanged.connect(self.textChanged)

但是不起作用 感谢您的关注

最佳答案

# Check changes on all lineEdit units
for n in range(2, 9):
    getattr(self, f"lineEdit_{n}").textChanged.connect(self.textChanged)

关于python - 是否可以通过将 lineEdit 插入 for 来缩短 PyQt5 中的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70403781/

相关文章:

python - MySQL 返回列的名称而不是值

python - 这个 lambda 有什么问题(也许与 PyQt 有关?)

python - 如何制作分割窗口?

python - 保存方法中的django回滚事务

python - Tensorflow卷积和numpy卷积的区别

python - 为什么带有自定义绘画的小部件不可见?

python - 带有可点击超链接的 PyQt5 工具提示?

python - 如何从索引列表中选择 QtableWidget 中的单元格

python - 什么是 Flask 中的 HTTP 400 错误请求

Python检索Windows服务信息