Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        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

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading