Python Forum
How to loop through all QLineEdit widgets on a form
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to loop through all QLineEdit widgets on a form
#1
Hello everyone,

Greetings from Brazil! Does anybody know a quick and easy way to loop through all QLineEdit widgets on a form and clear them? Thanks for your time and help. I really appreciate it.


This is how I am currently doing it:

    myform = {ui.lineEdit_name, ui.lineEdit_email, ui.lineEdit_pwd, ui.lineEdit_mktg, ... etc.}
    for fields in myform:
        fields.clear()
Best regards.
Reply
#2
Are you looking for something to build the "my_form" part of your example? How about using the focus chain?
my_form = []
w = some_widget
while not w in my_form:
    if isinstance(w, QLineEdit):
        my_form.append(w)
    w = w.nextInFocusChain()
I have not tried this code.

For form entry/editing usually the program has a way to load the form fields and clearing the form is done by loading an empty data.
Reply
#3
Hi Dean,

Nope. The form itself is already built. Please refer to the full code below. Thanks for your feedback! :)

import sys
from datetime import date, datetime
import pymongo.mongo_client
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import QMessageBox, QLineEdit

connection = pymongo.MongoClient('localhost', 27017)
database = connection['bremi691_ead']
collection = database['usuarios']

class UiDialog(object):
    def __init__(self):
        self.lineEdit_name = QtWidgets.QLineEdit(Dialog)
        self.lineEdit_email = QtWidgets.QLineEdit(Dialog)
        self.lineEdit_pwd = QtWidgets.QLineEdit(Dialog)
        self.lineEdit_mktg = QtWidgets.QLineEdit(Dialog)

        self.label_name = QtWidgets.QLabel(Dialog)
        self.label_email = QtWidgets.QLabel(Dialog)
        self.label_pwd = QtWidgets.QLabel(Dialog)
        self.label_mktg = QtWidgets.QLabel(Dialog)

    def setup_ui(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(448, 300)

        self.lineEdit_name.setGeometry(QtCore.QRect(140, 50, 241, 21))
        self.lineEdit_name.setInputMethodHints(QtCore.Qt.ImhUppercaseOnly)
        self.lineEdit_name.setObjectName("lineEdit_name")

        self.lineEdit_email.setGeometry(QtCore.QRect(140, 90, 191, 21))
        self.lineEdit_email.setInputMethodHints(QtCore.Qt.ImhEmailCharactersOnly)
        self.lineEdit_email.setObjectName("lineEdit_email")

        self.lineEdit_pwd.setGeometry(QtCore.QRect(140, 130, 131, 21))
        self.lineEdit_pwd.setInputMethodHints(QtCore.Qt.ImhSensitiveData | QtCore.Qt.ImhUppercaseOnly)
        self.lineEdit_pwd.setObjectName("lineEdit_pwd")

        self.lineEdit_mktg.setGeometry(QtCore.QRect(140, 170, 131, 21))
        self.lineEdit_mktg.setInputMethodHints(QtCore.Qt.ImhUppercaseOnly)
        self.lineEdit_mktg.setObjectName("lineEdit_mktg")

        self.label_name.setGeometry(QtCore.QRect(71, 50, 60, 16))
        self.label_name.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.label_name.setObjectName("label_name")

        self.label_email.setGeometry(QtCore.QRect(71, 90, 60, 16))
        self.label_email.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.label_email.setObjectName("label_email")

        self.label_pwd.setGeometry(QtCore.QRect(70, 130, 60, 16))
        self.label_pwd.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.label_pwd.setObjectName("label_pwd")

        self.label_mktg.setGeometry(QtCore.QRect(60, 170, 71, 20))
        self.label_mktg.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.label_mktg.setObjectName("label_mktg")

        button_ok = QtWidgets.QPushButton(Dialog)
        button_ok.setText("OK")
        button_ok.move(200, 225)
        button_ok.clicked.connect(insert_record)

        self.retranslate_ui(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslate_ui(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Add new student"))
        self.label_name.setText(_translate("Dialog", "Nome: "))
        self.label_email.setText(_translate("Dialog", "e-mail: "))
        self.label_pwd.setText(_translate("Dialog", "Senha:"))
        self.label_mktg.setText(_translate("Dialog", "Marketing:"))


def clear_all():
    my_form = {ui.lineEdit_name, ui.lineEdit_email, ui.lineEdit_pwd, ui.lineEdit_mktg}
    for fields in my_form: fields.clear()


def insert_record():
    try:
        if ui.lineEdit_name.text() and ui.lineEdit_email.text() and ui.lineEdit_pwd.text() and ui.lineEdit_mktg.text() != "":
            data = {'nome': ui.lineEdit_name.text(),
                    'email': ui.lineEdit_email.text(),
                    'senha': ui.lineEdit_pwd.text(),
                    'data_cadastro': datetime.today(),
                    'niveis_acesso_id': 1,
                    'validacao': 'sim',
                    'ativo': 0,
                    'como_chegou': ui.lineEdit_mktg.text()}
            collection.insert_one(data)
            clear_all()

            QMessageBox.information(None, "Informação:", "Dados adicionados com sucesso!")
        else:
            QMessageBox.warning(None, "Antenção:", "Por favor preencha os campos em branco!")
    except Exception:
        QMessageBox.critical(None, "Erro:", "Não foi possível inserir os dados.\n Cheque o servidor de dados.")


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = UiDialog()
    ui.setup_ui(Dialog)
    Dialog.show()
    sys.exit(app.exec_())
Reply
#4
Then I don't understand your question. Are you wondering if there is some Qt command that clears all widgets in a window? What part of your solution don't you like?
Reply
#5
What I don't like about my solution is having to list every single QLineEdit box on my forms in order to clear them. This particular form is ok, because it has just a few QLineEdit boxes on it, but some forms will have too many for me to clear one by one. There has got to be (hopefully) a smarter, more efficient way to accomplish this than the way I did it.
Reply
#6
The code I provided earlier generates a list of the QLineEdit objects for you. You don't have to type them in manually.

But I found a better way
for w in form.findChildren(QLineEdit):
    w.clear()
Reply
#7
Dean, you are a genious! It worked perfectly. Thank you very much for your time and help.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyQt] QLineEdit Caret (Text Cursor) Transparency malonn 5 2,798 Nov-04-2022, 09:04 PM
Last Post: malonn
  How to accept only float number in QLineEdit input ism 5 28,360 Jul-06-2021, 05:23 PM
Last Post: deanhystad
  Simple printing the text for a QLineEdit thewolf 16 7,840 Mar-06-2021, 11:37 PM
Last Post: deanhystad
  PyQt5: How to retrieve a QLineEdit by its name ? arbiel 4 7,863 Oct-21-2020, 02:35 PM
Last Post: arbiel
  Two QlineEdit box, which interrelated GMCobraz 1 2,411 Aug-14-2020, 07:15 PM
Last Post: deanhystad
  [PyQt] Dynamically add and remove QLineEdit's GMCobraz 3 7,153 Jun-23-2020, 07:01 PM
Last Post: Yoriz
  prompt for input in qlineedit GMCobraz 3 3,208 Jun-22-2020, 01:51 PM
Last Post: GMCobraz
  [PyQt] display content from left to right in QComboBox or QLineEdit mart79 2 2,302 May-30-2020, 04:38 PM
Last Post: Axel_Erfurt
  [PyQt] How to clear multiple Qlineedit in a loop mart79 6 7,731 Aug-15-2019, 02:37 PM
Last Post: Denni
  How to validate multiple QLineEdit widgets without addressing them separately? mart79 3 4,249 Aug-08-2019, 12:50 PM
Last Post: Denni

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020