简体   繁体   中英

Is it possible to shorten the code in PyQt5 by sticking lineEdit in for?

I have 7 lineEdit blocks, and I want the textChanged function to trigger when any of them change, I decided to take the easy route and write them out in order, but now I want to shorten my code.

I wanna shorted this

        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)

like this

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

or like this

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

but it does not work Thanks for your attention

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM