Search code examples
pythonpython-2.7qt4pyqt4

How to use findChildren?


I want to click a button and clear around 20 QLineEdits.

I am trying to use findChildren() and put all the QLineEdit in a QListWidget

self.StudentAdmissionLayout = QGridLayout()
self.StudentAdmissionLayout.addWidget(self.StudentName,1,0,1,1)

The self.StudentAdmissionLayout layout has all the QLineEdit placed on it.

self.myList = QListWidget()
self.Item = QListWidgetItem()
self.Item = self.StudentAdmissionLayout.findChildren(QLineEdit)
self.myList.addItem(self.Item)

I am getting below error:

TypeError: arguments did not match any overloaded call:
QListWidget.addItem(QListWidgetItem): argument 1 has unexpected type 'list'
QListWidget.addItem(QString): argument 1 has unexpected type 'list'

I am trying to put the above 4 lines in a loop. But the 3rd line isn't working, I am not sure how to make it work. Please suggest.


Solution

  • OK, we have to understand behavior of list-of-QObject QObject.findChildren (self, type type, QString name = QString()) . The documentation for this class says

    Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. Omitting the name argument causes all object names to be matched. The search is performed recursively.

    Source: http://pyqt.sourceforge.net/Docs/PyQt4/qobject.html#findChildren

    Then, it returns a Python list to you and each element in the list is type of T (the type you provided as input). So your problem:

    TypeError: arguments did not match any overloaded call:
    QListWidget.addItem(QListWidgetItem): argument 1 has unexpected type 'list'
    QListWidget.addItem(QString): argument 1 has unexpected type 'list'
    

    is because you pass a list, but addItem requires a QListWidgetItem or QString (or Python str). If you want to pass a Python list you must use a for loop to iterate over the data:

    myQListWidget = QListWidget()
    listsItem = ['my', 'data', 'are', 'here', '!']
    for item in listsItem:
        myQListWidget.addItem(item)
    

    Another problem I found is that your search data are QLineEdits , It isn’t a supported type in any overloaded method of QListWidget.addItem(). I think you can't pass it in to this method. But if you need the "text" in each QLineEdit only, you can convert it like this:

    self.studentAdmissionQGridLayout = QGridLayout()
    .
    .
    .
    self.myQListWidget = QListWidget()
    listsMyQLineEdit = self.studentAdmissionQGridLayout.findChildren(QLineEdit)
    for myQLineEdit in listsMyQLineEdit:
        self.myQListWidget.addItem(myQLineEdit.text())
    

    Here is a reference to help to understand QListWidget.addItem():

    http://pyqt.sourceforge.net/Docs/PyQt4/qlistwidget.html#addItem