Python Forum
[PyQt] How to clear multiple Qlineedit in a loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyQt] How to clear multiple Qlineedit in a loop
#1
How can you clear multiple Qlineedit in a loop or efficiently? I have about 30 Qlineedit in a GUI.
They all have a unique name starting with 'txt' such as 'txtNamePerson' and 'txtAgePerson.

However, of these 30 Qlineedit, only 20 need to be cleared. Can someone give advice?
Reply
#2
This is done when during creation
MyLineEditDict[key] = self.txtNamePerson
Then when you need to do something to them all you just do this
for key in MyLineEditDict.keys()
    MyLineEditDict[key].setText('None for All')
Note: key is whatever you want it to be since how it is being used means there is no need to care what it is, however, if you want to handle your LineEdits a bit more semi-sequential or perhaps more intuitively you could make it a numeric index of some sort. Regardless the basics of this would not change any just its particulars.
Reply
#3
(Aug-09-2019, 01:14 PM)Denni Wrote: This is done when during creation
MyLineEditDict[key] = self.txtNamePerson
Then when you need to do something to them all you just do this
for key in MyLineEditDict.keys()
    MyLineEditDict[key].setText('None for All')
Note: key is whatever you want it to be since how it is being used means there is no need to care what it is, however, if you want to handle your LineEdits a bit more semi-sequential or perhaps more intuitively you could make it a numeric index of some sort. Regardless the basics of this would not change any just its particulars.

Thanks for the help. However, this assumes that the QLineEdit can be indexed during creation. I am using a designer and I have no idea where to start.
I have been struggling some time now. The ui py file is used to call the respective QLineEdit.

Main .py file which needs to loop through the QLineEdit:
from PyQt5 import QtCore, QtGui, QtWidgets
from ui import Ui_Dialog
from PyQt5.QtWidgets import  QApplication, QTreeWidget, QTreeWidgetItem,  QComboBox
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QRegExpValidator
import numpy as np
import os

class Main(QtWidgets.QMainWindow, Ui_Dialog):
    def __init__(self, parent=None):
        self.current_directory = os.getcwd()
        self.regex = QRegExp("[0-9._]+")
        self.validator = QRegExpValidator(self.regex)

        super(Main, self).__init__(parent)
        self.setupUi(self)
        self.txtWeight.setValidator(self.validator)
        self.btnAddNew.clicked.connect(self.clearQLineEdit)
    
    def clearQLineEdit(self):
     ------ code that loops through the QLineEdit ---------
ui.py with the ui set-up:
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(342, 217)
        self.Details = QtWidgets.QGroupBox(Dialog)
        self.Details.setGeometry(QtCore.QRect(10, 10, 321, 201))
        self.Details.setObjectName("Details")
        self.Main = QtWidgets.QGroupBox(self.Details)
        self.Main.setGeometry(QtCore.QRect(10, 20, 301, 141))
        self.Main.setObjectName("Main")
        self.txtName = QtWidgets.QLineEdit(self.Main)
        self.txtName.setGeometry(QtCore.QRect(150, 20, 131, 20))
        self.txtName.setObjectName("txtName")
        self.label = QtWidgets.QLabel(self.Main)
        self.label.setGeometry(QtCore.QRect(10, 20, 51, 16))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.Main)
        self.label_2.setGeometry(QtCore.QRect(10, 50, 111, 16))
        self.label_2.setObjectName("label_2")
        self.txtWeight = QtWidgets.QLineEdit(self.Main)
        self.txtWeight.setGeometry(QtCore.QRect(150, 50, 61, 20))
        self.txtWeight.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
        self.txtWeight.setObjectName("txtWeight")
        self.txtYear = QtWidgets.QLineEdit(self.Main)
        self.txtYear.setGeometry(QtCore.QRect(150, 80, 61, 20))
        self.txtYear.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
        self.txtYear.setObjectName("txtYear")
        self.label_3 = QtWidgets.QLabel(self.Main)
        self.label_3.setGeometry(QtCore.QRect(10, 80, 111, 16))
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(self.Main)
        self.label_4.setGeometry(QtCore.QRect(90, 20, 51, 16))
        self.label_4.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(self.Main)
        self.label_5.setGeometry(QtCore.QRect(90, 50, 51, 16))
        self.label_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.label_5.setObjectName("label_5")
        self.label_6 = QtWidgets.QLabel(self.Main)
        self.label_6.setGeometry(QtCore.QRect(90, 80, 51, 16))
        self.label_6.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.label_6.setObjectName("label_6")
        self.txtPlace = QtWidgets.QLineEdit(self.Main)
        self.txtPlace.setGeometry(QtCore.QRect(150, 110, 61, 20))
        self.txtPlace.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
        self.txtPlace.setReadOnly(True)
        self.txtPlace.setObjectName("txtPlace")
        self.label_7 = QtWidgets.QLabel(self.Main)
        self.label_7.setGeometry(QtCore.QRect(10, 110, 111, 16))
        self.label_7.setObjectName("label_7")
        self.label_8 = QtWidgets.QLabel(self.Main)
        self.label_8.setGeometry(QtCore.QRect(90, 110, 51, 16))
        self.label_8.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.label_8.setObjectName("label_8")
        self.btnAddNewPipe = QtWidgets.QPushButton(self.Details)
        self.btnAddNewPipe.setGeometry(QtCore.QRect(230, 170, 75, 23))
        self.btnAddNewPipe.setObjectName("btnAddNew")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
        Dialog.setTabOrder(self.txtWeight, self.txtName)
        Dialog.setTabOrder(self.txtName, self.txtPlace)
        Dialog.setTabOrder(self.txtPlace, self.txtYear)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.Details.setTitle(_translate("Dialog", "Details"))
        self.Main.setTitle(_translate("Dialog", "Test"))
        self.label.setText(_translate("Dialog", "Name"))
        self.label_2.setText(_translate("Dialog", "Weight"))
        self.label_3.setText(_translate("Dialog", "Year"))
        self.label_4.setText(_translate("Dialog", "[-]"))
        self.label_5.setText(_translate("Dialog", "[kg]"))
        self.label_6.setText(_translate("Dialog", "[-]"))
        self.label_7.setText(_translate("Dialog", "Place"))
        self.label_8.setText(_translate("Dialog", "[-]"))
        self.btnAddNewPipe.setText(_translate("Dialog", "Add new"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())
Can you help me further?
Reply
#4
Okay I will look it over but my first and foremost suggestion would be to stop using the Designer as it does not produce quality code nor even code that is inline with how pyqt ought to be coded -- in a nutshell it is a fairly useless and poorly designed tool -- kind of like using a sledge hammer to drive a finishing nail it just either creates a big mess and/or requires extreme effort.

So basically what I will have to do is go through and rewrite your Designer code and show you how to proper way to write a pyqt GUI using the Layout system from here you might just be surprised how easy it is to figure out what to do and where to do it. Try to get it up a bit later today. I have done this a few times before, and the biggest time delay is usually deciphering the Designer's garbage code.

Lastly welcome to my classroom ;) -- oh and I have a Discord Message Server where I can be reached to help with python/pyqt if you are interested and/or have Discord available to you
Reply
#5
Okay I have restructured your Designer Code to be pyqt friendly mimicking what you had done as best that I could and added comments to help you perhaps understand better the various pieces and perhaps the why of them. I did not create the Dictionary nor finish the Clear method as I thought perhaps you would like to give it a go now that things are much more nicely laid out and you can hopefully have an easier time of figuring out where to put the items you need to add. But as I state within the code if you have any questions just ask -- but just keep in mind I would much rather teach you to fish than give you one ;)

# First never import more than you need it makes a program bigger
# than necessary and sometimes introduces hidden issues

# Now I rename the os and sys functions as this helps me see exactly
# where they are from and keeps them from stepping on the toes of any
# other functions that might be named similarly
from os  import getcwd as osGetcwd
from sys import exit   as sysExit

# I break up Widgets into these two categories to help clarify what each of
# the various Objects are used for further I try not to let the line get too
# long as you can see below but again I am only including the things we are 
# going to use within the program and nothing more also because all of PyQt5
# functions start with a capital Q I do not bother renaming and do not see a
# need to include their governing module (aka QtCore, QtGui, and QtWidgets)
from PyQt5.QtCore    import QRegExp, Qt
from PyQt5.QtGui     import QRegExpValidator
# Widget Container Objects
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QDockWidget
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QGridLayout, QGroupBox, QLabel
# Widget Action Objects
from PyQt5.QtWidgets import QLineEdit, QPushButton, QAction, QStyleFactory

# This is your Menu and Tool Bar class it does not handle the Tool Bar
# at this time but it could be expanded to do so fairly easily just 
# keep in mind everything on a Tool Bar should come from the Menu Bar 
class MenuToolBar(QDockWidget):
    def __init__(self, parent):
        QDockWidget.__init__(self)
        self.Parent = parent
        self.MainMenu = parent.menuBar()

      # This is used to have a handle to the Menu Items
      # should you implement a Tool Bar
        self.MenuActRef = {'HelloAct':0,
                           'ResetAct':0}

        # ******* Create the World Menu *******
        self.WorldMenu  = self.MainMenu.addMenu('World')

        # ******* Create World Menu Items *******
        self.HelloAct = QAction('&Hello', self)
      # In case you have or want to include an Icon
      #  self.HelloAct = QAction(QIcon('Images/hello.ico'), '&Hello', self)
        self.HelloAct.setShortcut("Ctrl+H")
        self.HelloAct.setStatusTip('Say Hello to the World')
        self.HelloAct.triggered.connect(self.SayHello)
        self.MenuActRef['HelloAct'] = self.HelloAct

        self.ResetAct = QAction('&Reset', self)
      #  self.ResetAct = QAction(QIcon('Images/reset.ico'), '&Hello', self)
        self.ResetAct.setShortcut("Ctrl+H")
        self.ResetAct.setStatusTip('Reset the Dialog')
        self.ResetAct.triggered.connect(self.ResetWorld)
        self.MenuActRef['ResetAct'] = self.ResetAct

        self.OkayAct = QAction('&Okay', self)
      #  self.OkayAct = QAction(QIcon('Images/okay.ico'), '&Okay', self)
        self.OkayAct.setShortcut("Ctrl+O")
        self.OkayAct.setStatusTip('Okay?')
        self.OkayAct.triggered.connect(self.ItsOkay)
        self.MenuActRef['OkayAct'] = self.OkayAct

        # ******* Setup the World Menu *******
        self.WorldMenu.addAction(self.HelloAct)
        self.WorldMenu.addSeparator()
        self.WorldMenu.addAction(self.ResetAct)
        self.WorldMenu.addSeparator()
        self.WorldMenu.addAction(self.OkayAct)
        
        self.InitToolBar()

    def InitToolBar(self):
      # If you create a Tool Bar initialize it here
        pass

# These are the Menu/Tool Bar Actions
# Note: The menu is not where things get done its only
# purpose is to set up and render the Menu and Tool Bars
# as such the Actions performed are Call Backs to the
# Main Handler since the Menu ought not know or care
# what its menu selections actually do (if anything)
# This thus makes your Menu/Tool Class autonomous
    def SayHello(self):
        self.Parent.MenuSubmit()

    def ResetWorld(self):
        self.Parent.MenuReset()

    def ItsOkay(self):
        self.Parent.MenuOkay()
 
class CenterPanel(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.Parent = parent
      # Note you only need the "self." handle attached to things
      # you plan to manipulate in code otherwise you can just 
      # create them and use them within the Gui without the putting
      # the handle on them like I have done with the QBoxes
        self.NumRegex = QRegExp("[0-9._]+")
        self.Validatr = QRegExpValidator(self.NumRegex)
        #-------
        self.lblName = QLabel()
        self.lblName.setText('Name')

        self.lblNamTyp = QLabel()
        self.lblNamTyp.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.lblNamTyp.setText('[-]')

        self.txtName = QLineEdit()
        #-------
        self.lblWeight = QLabel()
        self.lblWeight.setText('Weight')

        self.lblWgtTyp = QLabel()
        self.lblWgtTyp.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.lblWgtTyp.setText('[kg]')

        self.txtWeight = QLineEdit()
      # Redundant and/or conflicting with Validator
      #  self.txtWeight.setInputMethodHints(Qt.ImhDigitsOnly)
        self.txtWeight.setValidator(self.Validatr)
        #-------
        self.lblYear = QLabel()
        self.lblYear.setText('Year')

        self.lblYrTyp = QLabel()
        self.lblYrTyp.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.lblYrTyp.setText('[-]')

        self.txtYear = QLineEdit()
        self.txtYear.setInputMethodHints(Qt.ImhDigitsOnly)
        #-------
        self.lblPlace = QLabel()
        self.lblPlace.setText('Place')

        self.lblPlcTyp = QLabel()
        self.lblPlcTyp.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.lblPlcTyp.setText('[-]')

        self.txtPlace = QLineEdit()
        self.txtPlace.setInputMethodHints(Qt.ImhDigitsOnly)
        self.txtPlace.setReadOnly(True)
        #-------
        grdTest = QGridLayout()
        grdTest.addWidget(self.lblName,    0, 0)
        grdTest.addWidget(QLabel('     '), 0, 1)
        grdTest.addWidget(self.lblNamTyp,  0, 2)
        grdTest.addWidget(self.txtName,    0, 3)

        grdTest.addWidget(self.lblWeight,  1, 0)
        grdTest.addWidget(QLabel('     '), 1, 1)
        grdTest.addWidget(self.lblWgtTyp,  1, 2)
        grdTest.addWidget(self.txtWeight,  1, 3)

        grdTest.addWidget(self.lblYear,    2, 0)
        grdTest.addWidget(QLabel('     '), 2, 1)
        grdTest.addWidget(self.lblYrTyp,   2, 2)
        grdTest.addWidget(self.txtYear,    2, 3)

        grdTest.addWidget(self.lblPlace,   3, 0)
        grdTest.addWidget(QLabel('     '), 3, 1)
        grdTest.addWidget(self.lblPlcTyp,  3, 2)
        grdTest.addWidget(self.txtPlace,   3, 3)
        #-------
        gbxTest = QGroupBox()
        gbxTest.setTitle('Test')
        gbxTest.setLayout(grdTest)
        #-------
        self.lblHidden = QLabel('')
        self.HideSet = False

        self.btnAddNew = QPushButton()
        self.btnAddNew.setText('Add New')
        self.btnAddNew.clicked.connect(self.ClearValues)

        hbxAddNew = QHBoxLayout()
        hbxAddNew.addWidget(self.lblHidden)
        hbxAddNew.addStretch(2)
        hbxAddNew.addWidget(self.btnAddNew)
        #-------
        vbxAll = QVBoxLayout()
        vbxAll.addWidget(gbxTest)
        vbxAll.addLayout(hbxAddNew)
        #-------
        gbxDetails = QGroupBox()
        gbxDetails.setTitle('Details')
        gbxDetails.setLayout(vbxAll)
        #-------
        hbxFinal = QHBoxLayout()
        hbxFinal.addWidget(gbxDetails)
        #-------
        self.setLayout(hbxFinal)

    def HandleSubmit(self):
        if self.HideSet:
            self.HideSet = False
            self.lblHidden.setText('')
        else:
            self.HideSet = True
            self.lblHidden.setText('Menu Submit')

    def ClearValues(self):
     # ------ Code that will loop through the QLineEdits ---------
     # I am leaving this for you to give a stab at now that 
     # everything I hope is much easier to understand but 
     # feel free to ask questions if you need assistance
        pass

# Note while denoted as the MainWindow in this situation it is more
# your main handler and as such it is best to restrict it to doing
# just that and let other classes handle the other stuff -- it also
# helps to maintain the overall perspective of what each piece has
# been designed for
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
    
      # MainWindow is made up of 4 areas Menu Bar, Tool Bar, Center Pane, & Status Bar
      # It also contains a border region for dockable widget windows
      # These are mostly the only things that should appear within your MainWindow
      # Yes there might be a few other things but again the purpose of this class is
      # to be your Main Coordinator mostly
        self.setWindowTitle('Main')
      # Note if you are going to be manipulating files with this it should be moved
      # to within the module you create to handle that kind of stuff but if you are
      # not going to use it then just remove it entirely as it does nothing and can
      # always be added later if desired
        self.CurntDir = osGetcwd()

      # Sometimes its best to place the window where you want but just setting its size 
      # works as well - I have included both just use the one you prefer
        WinLeft = 150; WinTop = 150; WinWidth = 340; WinHight = 220
        self.setGeometry(WinLeft, WinTop, WinWidth, WinHight)
        # self.resize(WinWidth, WinHight)

        self.CenterPane = CenterPanel(self)
        self.setCentralWidget(self.CenterPane)

      # The Menu and Tool Bar for your MainWindow should be classed as well
        self.MenuBar = MenuToolBar(self)

        self.SetStatusBar(self)
      # Not exactly sure what all this does yet but it does remove 
      # oddities from the window so I always include it - for now
        self.setStyle(QStyleFactory.create('Cleanlooks'))

    def SetStatusBar(self, parent):
        StatusMsg = ''
        parent.StatBar = parent.statusBar()

        if len(StatusMsg) < 1:
          # This will disappear once you view any menu items
            StatusMsg = 'Ready'

        parent.StatBar.showMessage(StatusMsg)

    def MenuSubmit(self):
      # This redirects the Menu Action to the appropriate module
      # currently you only have one other module but if you had
      # more than one or if this was something that needed to be
      # handled here it would be set up differently
        self.CenterPane.HandleSubmit()

    def MenuReset(self):
      # This one actually performs the action
        self.StatBar.showMessage('Main Menu Reset Action')
       
    def MenuOkay(self):
      # An example of a Menu Call Back that does nothing but again
      # the Menu does not know this or even care
        pass
 
if __name__ == "__main__":
  # It is best to keep this function to its bare minimum as its 
  # main purpose is to handle pre-processing stuff
  # 
  # Next you did not appear to be using sys.argv but if you do need 
  # to use command line arguments I strongly suggest you look into 
  # argparse its a python library and very helpful for this as such 
  # also much cleaner than dealing with them via regular means
  # otherwise do not include more in your program than you are going
  # to actually use -- it creates unnecessary confusion down the road
    MainThred = QApplication([])

    MainGui = MainWindow()
    MainGui.show()

    sysExit(MainThred.exec_())
Reply
#6
(Aug-13-2019, 06:12 PM)Denni Wrote: Okay I have restructured your Designer Code to be pyqt friendly mimicking what you had done as best that I could and added comments to help you perhaps understand better the various pieces and perhaps the why of them. I did not create the Dictionary nor finish the Clear method as I thought perhaps you would like to give it a go now that things are much more nicely laid out and you can hopefully have an easier time of figuring out where to put the items you need to add. But as I state within the code if you have any questions just ask -- but just keep in mind I would much rather teach you to fish than give you one ;)

# First never import more than you need it makes a program bigger
# than necessary and sometimes introduces hidden issues

# Now I rename the os and sys functions as this helps me see exactly
# where they are from and keeps them from stepping on the toes of any
# other functions that might be named similarly
from os  import getcwd as osGetcwd
from sys import exit   as sysExit

# I break up Widgets into these two categories to help clarify what each of
# the various Objects are used for further I try not to let the line get too
# long as you can see below but again I am only including the things we are 
# going to use within the program and nothing more also because all of PyQt5
# functions start with a capital Q I do not bother renaming and do not see a
# need to include their governing module (aka QtCore, QtGui, and QtWidgets)
from PyQt5.QtCore    import QRegExp, Qt
from PyQt5.QtGui     import QRegExpValidator
# Widget Container Objects
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QDockWidget
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QGridLayout, QGroupBox, QLabel
# Widget Action Objects
from PyQt5.QtWidgets import QLineEdit, QPushButton, QAction, QStyleFactory

# This is your Menu and Tool Bar class it does not handle the Tool Bar
# at this time but it could be expanded to do so fairly easily just 
# keep in mind everything on a Tool Bar should come from the Menu Bar 
class MenuToolBar(QDockWidget):
    def __init__(self, parent):
        QDockWidget.__init__(self)
        self.Parent = parent
        self.MainMenu = parent.menuBar()

      # This is used to have a handle to the Menu Items
      # should you implement a Tool Bar
        self.MenuActRef = {'HelloAct':0,
                           'ResetAct':0}

        # ******* Create the World Menu *******
        self.WorldMenu  = self.MainMenu.addMenu('World')

        # ******* Create World Menu Items *******
        self.HelloAct = QAction('&Hello', self)
      # In case you have or want to include an Icon
      #  self.HelloAct = QAction(QIcon('Images/hello.ico'), '&Hello', self)
        self.HelloAct.setShortcut("Ctrl+H")
        self.HelloAct.setStatusTip('Say Hello to the World')
        self.HelloAct.triggered.connect(self.SayHello)
        self.MenuActRef['HelloAct'] = self.HelloAct

        self.ResetAct = QAction('&Reset', self)
      #  self.ResetAct = QAction(QIcon('Images/reset.ico'), '&Hello', self)
        self.ResetAct.setShortcut("Ctrl+H")
        self.ResetAct.setStatusTip('Reset the Dialog')
        self.ResetAct.triggered.connect(self.ResetWorld)
        self.MenuActRef['ResetAct'] = self.ResetAct

        self.OkayAct = QAction('&Okay', self)
      #  self.OkayAct = QAction(QIcon('Images/okay.ico'), '&Okay', self)
        self.OkayAct.setShortcut("Ctrl+O")
        self.OkayAct.setStatusTip('Okay?')
        self.OkayAct.triggered.connect(self.ItsOkay)
        self.MenuActRef['OkayAct'] = self.OkayAct

        # ******* Setup the World Menu *******
        self.WorldMenu.addAction(self.HelloAct)
        self.WorldMenu.addSeparator()
        self.WorldMenu.addAction(self.ResetAct)
        self.WorldMenu.addSeparator()
        self.WorldMenu.addAction(self.OkayAct)
        
        self.InitToolBar()

    def InitToolBar(self):
      # If you create a Tool Bar initialize it here
        pass

# These are the Menu/Tool Bar Actions
# Note: The menu is not where things get done its only
# purpose is to set up and render the Menu and Tool Bars
# as such the Actions performed are Call Backs to the
# Main Handler since the Menu ought not know or care
# what its menu selections actually do (if anything)
# This thus makes your Menu/Tool Class autonomous
    def SayHello(self):
        self.Parent.MenuSubmit()

    def ResetWorld(self):
        self.Parent.MenuReset()

    def ItsOkay(self):
        self.Parent.MenuOkay()
 
class CenterPanel(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.Parent = parent
      # Note you only need the "self." handle attached to things
      # you plan to manipulate in code otherwise you can just 
      # create them and use them within the Gui without the putting
      # the handle on them like I have done with the QBoxes
        self.NumRegex = QRegExp("[0-9._]+")
        self.Validatr = QRegExpValidator(self.NumRegex)
        #-------
        self.lblName = QLabel()
        self.lblName.setText('Name')

        self.lblNamTyp = QLabel()
        self.lblNamTyp.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.lblNamTyp.setText('[-]')

        self.txtName = QLineEdit()
        #-------
        self.lblWeight = QLabel()
        self.lblWeight.setText('Weight')

        self.lblWgtTyp = QLabel()
        self.lblWgtTyp.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.lblWgtTyp.setText('[kg]')

        self.txtWeight = QLineEdit()
      # Redundant and/or conflicting with Validator
      #  self.txtWeight.setInputMethodHints(Qt.ImhDigitsOnly)
        self.txtWeight.setValidator(self.Validatr)
        #-------
        self.lblYear = QLabel()
        self.lblYear.setText('Year')

        self.lblYrTyp = QLabel()
        self.lblYrTyp.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.lblYrTyp.setText('[-]')

        self.txtYear = QLineEdit()
        self.txtYear.setInputMethodHints(Qt.ImhDigitsOnly)
        #-------
        self.lblPlace = QLabel()
        self.lblPlace.setText('Place')

        self.lblPlcTyp = QLabel()
        self.lblPlcTyp.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.lblPlcTyp.setText('[-]')

        self.txtPlace = QLineEdit()
        self.txtPlace.setInputMethodHints(Qt.ImhDigitsOnly)
        self.txtPlace.setReadOnly(True)
        #-------
        grdTest = QGridLayout()
        grdTest.addWidget(self.lblName,    0, 0)
        grdTest.addWidget(QLabel('     '), 0, 1)
        grdTest.addWidget(self.lblNamTyp,  0, 2)
        grdTest.addWidget(self.txtName,    0, 3)

        grdTest.addWidget(self.lblWeight,  1, 0)
        grdTest.addWidget(QLabel('     '), 1, 1)
        grdTest.addWidget(self.lblWgtTyp,  1, 2)
        grdTest.addWidget(self.txtWeight,  1, 3)

        grdTest.addWidget(self.lblYear,    2, 0)
        grdTest.addWidget(QLabel('     '), 2, 1)
        grdTest.addWidget(self.lblYrTyp,   2, 2)
        grdTest.addWidget(self.txtYear,    2, 3)

        grdTest.addWidget(self.lblPlace,   3, 0)
        grdTest.addWidget(QLabel('     '), 3, 1)
        grdTest.addWidget(self.lblPlcTyp,  3, 2)
        grdTest.addWidget(self.txtPlace,   3, 3)
        #-------
        gbxTest = QGroupBox()
        gbxTest.setTitle('Test')
        gbxTest.setLayout(grdTest)
        #-------
        self.lblHidden = QLabel('')
        self.HideSet = False

        self.btnAddNew = QPushButton()
        self.btnAddNew.setText('Add New')
        self.btnAddNew.clicked.connect(self.ClearValues)

        hbxAddNew = QHBoxLayout()
        hbxAddNew.addWidget(self.lblHidden)
        hbxAddNew.addStretch(2)
        hbxAddNew.addWidget(self.btnAddNew)
        #-------
        vbxAll = QVBoxLayout()
        vbxAll.addWidget(gbxTest)
        vbxAll.addLayout(hbxAddNew)
        #-------
        gbxDetails = QGroupBox()
        gbxDetails.setTitle('Details')
        gbxDetails.setLayout(vbxAll)
        #-------
        hbxFinal = QHBoxLayout()
        hbxFinal.addWidget(gbxDetails)
        #-------
        self.setLayout(hbxFinal)

    def HandleSubmit(self):
        if self.HideSet:
            self.HideSet = False
            self.lblHidden.setText('')
        else:
            self.HideSet = True
            self.lblHidden.setText('Menu Submit')

    def ClearValues(self):
     # ------ Code that will loop through the QLineEdits ---------
     # I am leaving this for you to give a stab at now that 
     # everything I hope is much easier to understand but 
     # feel free to ask questions if you need assistance
        pass

# Note while denoted as the MainWindow in this situation it is more
# your main handler and as such it is best to restrict it to doing
# just that and let other classes handle the other stuff -- it also
# helps to maintain the overall perspective of what each piece has
# been designed for
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
    
      # MainWindow is made up of 4 areas Menu Bar, Tool Bar, Center Pane, & Status Bar
      # It also contains a border region for dockable widget windows
      # These are mostly the only things that should appear within your MainWindow
      # Yes there might be a few other things but again the purpose of this class is
      # to be your Main Coordinator mostly
        self.setWindowTitle('Main')
      # Note if you are going to be manipulating files with this it should be moved
      # to within the module you create to handle that kind of stuff but if you are
      # not going to use it then just remove it entirely as it does nothing and can
      # always be added later if desired
        self.CurntDir = osGetcwd()

      # Sometimes its best to place the window where you want but just setting its size 
      # works as well - I have included both just use the one you prefer
        WinLeft = 150; WinTop = 150; WinWidth = 340; WinHight = 220
        self.setGeometry(WinLeft, WinTop, WinWidth, WinHight)
        # self.resize(WinWidth, WinHight)

        self.CenterPane = CenterPanel(self)
        self.setCentralWidget(self.CenterPane)

      # The Menu and Tool Bar for your MainWindow should be classed as well
        self.MenuBar = MenuToolBar(self)

        self.SetStatusBar(self)
      # Not exactly sure what all this does yet but it does remove 
      # oddities from the window so I always include it - for now
        self.setStyle(QStyleFactory.create('Cleanlooks'))

    def SetStatusBar(self, parent):
        StatusMsg = ''
        parent.StatBar = parent.statusBar()

        if len(StatusMsg) < 1:
          # This will disappear once you view any menu items
            StatusMsg = 'Ready'

        parent.StatBar.showMessage(StatusMsg)

    def MenuSubmit(self):
      # This redirects the Menu Action to the appropriate module
      # currently you only have one other module but if you had
      # more than one or if this was something that needed to be
      # handled here it would be set up differently
        self.CenterPane.HandleSubmit()

    def MenuReset(self):
      # This one actually performs the action
        self.StatBar.showMessage('Main Menu Reset Action')
       
    def MenuOkay(self):
      # An example of a Menu Call Back that does nothing but again
      # the Menu does not know this or even care
        pass
 
if __name__ == "__main__":
  # It is best to keep this function to its bare minimum as its 
  # main purpose is to handle pre-processing stuff
  # 
  # Next you did not appear to be using sys.argv but if you do need 
  # to use command line arguments I strongly suggest you look into 
  # argparse its a python library and very helpful for this as such 
  # also much cleaner than dealing with them via regular means
  # otherwise do not include more in your program than you are going
  # to actually use -- it creates unnecessary confusion down the road
    MainThred = QApplication([])

    MainGui = MainWindow()
    MainGui.show()

    sysExit(MainThred.exec_())

Much appreciated! I will see if I can manage to understand what you did :) but, that is for tomorrow. I will keep you posted.

I am not that experienced, but I tried to understand your structure and I am able to understand it to a certain point.
Hence, I tried (with some help from the internet) to include the clear option by adjusting the code but, it unfortunately does not work.
Most likely because I still miss some important knowledge or taking it a step to far to quickly....

class CenterPanel (QWidget):
    def __init__(self, parent):
        QWidget.__init__ (self)
        self.Parent = parent
        # Note you only need the "self." handle attached to things
        # you plan to manipulate in code otherwise you can just
        # create them and use them within the Gui without the putting
        # the handle on them like I have done with the QBoxes
        self.NumRegex = QRegExp ("[0-9._]+")
        self.Validatr = QRegExpValidator (self.NumRegex)
        self.txtNames = {}
        # -------
        self.lblName = QLabel ()
        self.lblName.setText ('Name')

        self.lblNamTyp = QLabel ()
        self.lblNamTyp.setAlignment (Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        self.lblNamTyp.setText ('[-]')

        self.txtName = QLineEdit ()
        # -------
        self.lblWeight = QLabel ()
        self.lblWeight.setText ('Weight')

        self.lblWgtTyp = QLabel ()
        self.lblWgtTyp.setAlignment (Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        self.lblWgtTyp.setText ('[kg]')

        self.txtWeight = QLineEdit ()
        # Redundant and/or conflicting with Validator
        #  self.txtWeight.setInputMethodHints(Qt.ImhDigitsOnly)
        self.txtWeight.setValidator (self.Validatr)
        # -------
        self.lblYear = QLabel ()
        self.lblYear.setText ('Year')

        self.lblYrTyp = QLabel ()
        self.lblYrTyp.setAlignment (Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        self.lblYrTyp.setText ('[-]')

        self.txtYear = QLineEdit ()
        self.txtYear.setInputMethodHints (Qt.ImhDigitsOnly)
        # -------
        self.lblPlace = QLabel ()
        self.lblPlace.setText ('Place')

        self.lblPlcTyp = QLabel ()
        self.lblPlcTyp.setAlignment (Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        self.lblPlcTyp.setText ('[-]')

        self.txtPlace = QLineEdit ()
        self.txtPlace.setInputMethodHints (Qt.ImhDigitsOnly)

        # -------
        grdTest = QGridLayout ()
        grdTest.addWidget (self.lblName, 0, 0)
        grdTest.addWidget (QLabel ('     '), 0, 1)
        grdTest.addWidget (self.lblNamTyp, 0, 2)
        grdTest.addWidget (self.txtName, 0, 3)

        self.txtNames = {'txtName':''}

        grdTest.addWidget (self.lblWeight, 1, 0)
        grdTest.addWidget (QLabel ('     '), 1, 1)
        grdTest.addWidget (self.lblWgtTyp, 1, 2)
        grdTest.addWidget (self.txtWeight, 1, 3)

        grdTest.addWidget (self.lblYear, 2, 0)
        grdTest.addWidget (QLabel ('     '), 2, 1)
        grdTest.addWidget (self.lblYrTyp, 2, 2)
        grdTest.addWidget (self.txtYear, 2, 3)

        grdTest.addWidget (self.lblPlace, 3, 0)
        grdTest.addWidget (QLabel ('     '), 3, 1)
        grdTest.addWidget (self.lblPlcTyp, 3, 2)
        grdTest.addWidget (self.txtPlace, 3, 3)
        # -------
        gbxTest = QGroupBox ()
        gbxTest.setTitle ('Test')
        gbxTest.setLayout (grdTest)
        # -------
        self.lblHidden = QLabel ('')
        self.HideSet = False

        self.btnAddNew = QPushButton ()
        self.btnAddNew.setText ('Add New')
        self.btnAddNew.clicked.connect (self.ClearValues)

        hbxAddNew = QHBoxLayout ()
        hbxAddNew.addWidget (self.lblHidden)
        hbxAddNew.addStretch (2)
        hbxAddNew.addWidget (self.btnAddNew)
        # -------
        vbxAll = QVBoxLayout ()
        vbxAll.addWidget (gbxTest)
        vbxAll.addLayout (hbxAddNew)
        # -------
        gbxDetails = QGroupBox ()
        gbxDetails.setTitle ('Details')
        gbxDetails.setLayout (vbxAll)
        # -------
        hbxFinal = QHBoxLayout ()
        hbxFinal.addWidget (gbxDetails)
        # -------
        self.setLayout (hbxFinal)

    def HandleSubmit(self):
        if self.HideSet:
            self.HideSet = False
            self.lblHidden.setText ('')
        else:
            self.HideSet = True
            self.lblHidden.setText ('Menu Submit')

    def ClearValues(self):
        # ------ Code that will loop through the QLineEdits ---------
        # I am leaving this for you to give a stab at now that
        # everything I hope is much easier to understand but
        # feel free to ask questions if you need assistance

        for item in self.txtNames.keys():
            getattr(self.Parent, item).setText(self.txtNames[item])
To summarise, I added the following lines: 11,61,121,122
Which results in the following error:
Error:
Traceback (most recent call last): File "C:/Users/Usr/Desktop/Work Folder PPM/VirtualEnvironment/Scripts/TestDenni.py", line 216, in ClearValues getattr(self.Parent, item).setText(self.txtNames[item]) AttributeError: 'MainWindow' object has no attribute 'txtName'
Reply
#7
Well you gave it a stab that I can respect ;) -- your method though was a bit overly complex and while it could be made to work there is a much simpler way of doing this. Because you have to define each of these objects via code then it is much more efficient to simply put them into the dictionary at the time of creation right after you create them as follows:

Note I removed all the extra inessential things that were not focused on this specific issue but you can easily add them back in if you want the full monty.

Oh and I also changed the name of your variable self.txtNames{} to something more appropriate to what it was and what it was holding self.dctTextHndl{} -- The dct part is short for Dictionary as opposed to a List or lst. TextHndl is short for Textbox Handle -- now it could have been abbreviated however you wanted but whatever you end up using you should do your best to stay consistent as this makes it easier to read your code a month or two down the road. Oh and keeping them short rather than verbose (dictionaryTextboxHandle) makes your code also easier to read as that stuff can get obscenely long.

from sys import exit   as sysExit

from PyQt5.QtCore    import QRegExp, Qt
from PyQt5.QtGui     import QRegExpValidator
# Widget Container Objects
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QDockWidget
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QGridLayout, QGroupBox, QLabel
# Widget Action Objects
from PyQt5.QtWidgets import QLineEdit, QPushButton, QAction, QStyleFactory

class CenterPanel(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.Parent = parent

        self.NumRegex = QRegExp("[0-9._]+")
        self.Validatr = QRegExpValidator(self.NumRegex)
        self.dctTextHndl = {}

        # -------
        self.lblName = QLabel()
        self.lblName.setText('Name')
 
        self.lblNamTyp = QLabel()
        self.lblNamTyp.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        self.lblNamTyp.setText ('[-]')
 
        self.txtName = QLineEdit()
        self.dctTextHndl[0] = self.txtName
        # -------
        self.lblWeight = QLabel()
        self.lblWeight.setText ('Weight')
 
        self.lblWgtTyp = QLabel()
        self.lblWgtTyp.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        self.lblWgtTyp.setText('[kg]')
 
        self.txtWeight = QLineEdit()
        self.txtWeight.setValidator(self.Validatr)
        self.dctTextHndl[1] = self.txtWeight
        # -------
        self.lblYear = QLabel()
        self.lblYear.setText('Year')
 
        self.lblYrTyp = QLabel()
        self.lblYrTyp.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        self.lblYrTyp.setText ('[-]')
 
        self.txtYear = QLineEdit()
        self.txtYear.setInputMethodHints(Qt.ImhDigitsOnly)
        self.dctTextHndl[2] = self.txtYear
        # -------
        self.lblPlace = QLabel()
        self.lblPlace.setText('Place')
 
        self.lblPlcTyp = QLabel()
        self.lblPlcTyp.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        self.lblPlcTyp.setText ('[-]')
 
        self.txtPlace = QLineEdit()
        self.txtPlace.setInputMethodHints(Qt.ImhDigitsOnly)
        self.dctTextHndl[3] = self.txtPlace
        # -------
        grdTest = QGridLayout()
        grdTest.addWidget(self.lblName, 0, 0)
        grdTest.addWidget(QLabel('     '), 0, 1)
        grdTest.addWidget(self.lblNamTyp, 0, 2)
        grdTest.addWidget(self.txtName, 0, 3)
 
        grdTest.addWidget(self.lblWeight, 1, 0)
        grdTest.addWidget(QLabel('     '), 1, 1)
        grdTest.addWidget(self.lblWgtTyp, 1, 2)
        grdTest.addWidget(self.txtWeight, 1, 3)
 
        grdTest.addWidget(self.lblYear, 2, 0)
        grdTest.addWidget(QLabel('     '), 2, 1)
        grdTest.addWidget(self.lblYrTyp, 2, 2)
        grdTest.addWidget(self.txtYear, 2, 3)
 
        grdTest.addWidget(self.lblPlace, 3, 0)
        grdTest.addWidget(QLabel('     '), 3, 1)
        grdTest.addWidget(self.lblPlcTyp, 3, 2)
        grdTest.addWidget(self.txtPlace, 3, 3)
        # -------
        gbxTest = QGroupBox()
        gbxTest.setTitle('Test')
        gbxTest.setLayout(grdTest)
        # -------
        self.lblHidden = QLabel('')
        self.HideSet = False
 
        self.btnAddNew = QPushButton()
        self.btnAddNew.setText('Add New')
        self.btnAddNew.clicked.connect(self.ClearValues)
 
        hbxAddNew = QHBoxLayout()
        hbxAddNew.addWidget(self.lblHidden)
        hbxAddNew.addStretch(2)
        hbxAddNew.addWidget(self.btnAddNew)
        # -------
        vbxAll = QVBoxLayout()
        vbxAll.addWidget(gbxTest)
        vbxAll.addLayout(hbxAddNew)
        # -------
        gbxDetails = QGroupBox()
        gbxDetails.setTitle('Details')
        gbxDetails.setLayout(vbxAll)
        # -------
        hbxFinal = QHBoxLayout()
        hbxFinal.addWidget(gbxDetails)
        # -------
        self.setLayout(hbxFinal)
 
    def ClearValues(self):
        for idx in range(0, 4):
            self.dctTextHndl[idx].clear()
            
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
     
        self.setWindowTitle('Main')
 
        WinLeft = 150; WinTop = 150; WinWidth = 340; WinHight = 220
        self.setGeometry(WinLeft, WinTop, WinWidth, WinHight)
 
        self.CenterPane = CenterPanel(self)
        self.setCentralWidget(self.CenterPane)
        self.setStyle(QStyleFactory.create('Cleanlooks'))
  
if __name__ == "__main__":
    MainThred = QApplication([])
 
    MainGui = MainWindow()
    MainGui.show()
 
    sysExit(MainThred.exec_())
So as you can see each time a Text Box object is created its handle is put into the object dictionary using a numeric key (any key will work but the numeric one is clearest and easiest when iterating through the dictionary later on) but this is not always the case -- just works best for this one. Still you could have done that function as follows -- which might have been better as its more generic and more pythonic:

    def ClearValues(self):
        for Key in self.dctTextHndl.keys():
            self.dctTextHndl[Key].clear()
Then in the ClearValues function we iterate through the dictionary using the Idx key (or just the Key in the 2nd one) which gives us the object handle and once we have that handle to the Text object we call that objects .clear() method.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyQt] QLineEdit Caret (Text Cursor) Transparency malonn 5 2,731 Nov-04-2022, 09:04 PM
Last Post: malonn
  How to accept only float number in QLineEdit input ism 5 28,115 Jul-06-2021, 05:23 PM
Last Post: deanhystad
  Simple printing the text for a QLineEdit thewolf 16 7,655 Mar-06-2021, 11:37 PM
Last Post: deanhystad
  PyQt5: How to retrieve a QLineEdit by its name ? arbiel 4 7,742 Oct-21-2020, 02:35 PM
Last Post: arbiel
  Two QlineEdit box, which interrelated GMCobraz 1 2,370 Aug-14-2020, 07:15 PM
Last Post: deanhystad
  [PyQt] Dynamically add and remove QLineEdit's GMCobraz 3 7,087 Jun-23-2020, 07:01 PM
Last Post: Yoriz
  prompt for input in qlineedit GMCobraz 3 3,156 Jun-22-2020, 01:51 PM
Last Post: GMCobraz
  [PyQt] display content from left to right in QComboBox or QLineEdit mart79 2 2,250 May-30-2020, 04:38 PM
Last Post: Axel_Erfurt
  How to loop through all QLineEdit widgets on a form JayCee 6 6,595 Apr-03-2020, 12:15 AM
Last Post: JayCee
  How to validate multiple QLineEdit widgets without addressing them separately? mart79 3 4,183 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