0

I'm currently trying out PyQt. A part of my application should contain input fields (QLineEdits). In this fields a user can enter a value and a label gives him a feedback if the input is a number. I create the QLineEdit and the corresponding labels in a for-loop with the following code:

for i in range(4):
    edit = QLineEdit()
    msgLabel = QLabel("")
    layout.addWidget(edit,i,0)
    layout.addWidget(msgLabel,i,1)
    edit.textChanged[str].connect(checkIfNumber(msgLabel,edit.text()))

My problem is that only the last element is concidered. Each element has the connect but only the text of the 4th element and the 4th label are used. How can I fix this problem? Thank you!

Brudi_Voeller
  • 91
  • 2
  • 11
  • You are overwriting the reference to the previous widgets on each iteration of your loop. Your usage of connecting to the QLineEdit signal is wrong as well. – Alexander Nov 04 '22 at 23:14
  • What would be a good practice for this problem? – Brudi_Voeller Nov 04 '22 at 23:20
  • depends on how you will be using them and how you plan to update them. Usually appending them to a list or dictionary would do but not for every situation – Alexander Nov 04 '22 at 23:25
  • @Brudi_Voeller signal connections must use *callables*. So, unless *calling* `checkIfNumber()` *returns* a function (but I sincerely doubt it), the connection is wrong. Use a lambda with keyworded arguments (otherwise you'll always get the last reference). – musicamante Nov 05 '22 at 00:29
  • `edit.textChanged.connect(lambda txt, lbl=msgLabel: checkIfNumber(lbl, txt))`. – ekhumoro Nov 05 '22 at 01:04

0 Answers0