Kenneth Lynch
Kenneth Lynch

Reputation: 31

Iterate over line edit widgets in order

I have a piece of code that iterates over LineEdit widgets to build a string. The problem that I having is that it seems to iterate randomly making parsing the string very difficult.

for widget in qApp.allWidgets():
    if isinstance(widget, QLineEdit):
       insertQuery += widget.displayText()

Upvotes: 0

Views: 798

Answers (2)

Kenneth Lynch
Kenneth Lynch

Reputation: 31

Ok I have a solution thanks to @mFoxRU

First I set objectName in the loop to create the line edit objects

LineEdit.setObjectName(str(i))

Then I use FocusOut to set value of line edit objects to a dictionary

LEDict = {'1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': '', '9': '', '10': '', '11': '', '12': ''}
if event.type() == QEvent.FocusOut:
            LEDict[widget.objectName()] = widget.displayText()
            return False

Finally, I iterate over the dictionary using range which I can use to construct the sql statement

for i in range(12):
            x = i + 1
            print(LEDict[str(x)])

Actually, I have eliminated the for loop in favor of a single statement that calls the dictionary elements directly to construct the sql code.

testInsert = "Insert INTO address VALUES(" + LEDict["1"] + ", " + LEDict["2"] + ")"

Upvotes: 0

mFoxRU
mFoxRU

Reputation: 490

allWidgets() does not guarantee any particular order. There are couple of ways to achieve your goal.

  • You may manually create a list of widgets and iterate over it.
  • You can specify tab order and use nextInFocusChain() to move to the next item on order.
  • Add some property with order number and collect text values to dict with order number as key, and join values afterwards.
  • Similarly to previous variant, you may use some naming convention for QLineEdit like adding order number to widget's objectName

Which way you will choose is up to you and depends on how you are creating UI.

Upvotes: 1

Related Questions