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

Time:12-18

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

CodePudding user response:

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