Python Forum

Full Version: How to loop through all QLineEdit widgets on a form
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
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.
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_())
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?
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.
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()
Dean, you are a genious! It worked perfectly. Thank you very much for your time and help.