birdmw
birdmw

Reputation: 875

PyQt4 filter by text on a QListView using setRowHidden

I have a dialog which looks like this:

enter image description here

That dialog has the following code connected to the filter button:

class Dialog(QtGui.QDialog, addWin.Ui_Dialog):
    ...
    self.list = QListView()
    self.filter.clicked.connect(self.filterClicked)
    ...
    def filterClicked(self):
        filter_text = str(self.lineEdit.text()).lower()
        for row in range(self.model.rowCount()):
            if filter_text in str(self.model.item(row).text()).lower():
                self.list.setRowHidden(row, True)
            else:
                self.list.setRowHidden(row, False)

However, when I click "Filter", nothing happens. What am I missing?

Upvotes: 3

Views: 3008

Answers (1)

eyllanesc
eyllanesc

Reputation: 243983

The problem is that you are hiding the wrong items. I have shown an example to show the solution.

class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent=parent)
        vLayout = QVBoxLayout(self)
        hLayout = QHBoxLayout()

        self.lineEdit = QLineEdit(self)
        hLayout.addWidget(self.lineEdit)    

        self.filter = QPushButton("filter", self)
        hLayout.addWidget(self.filter)
        self.filter.clicked.connect(self.filterClicked)

        self.list = QListView(self)

        vLayout.addLayout(hLayout)
        vLayout.addWidget(self.list)

        self.model = QStandardItemModel(self.list)

        codes = [
            'LOAA-05379',
            'LOAA-04468',
            'LOAA-03553',
            'LOAA-02642',
            'LOAA-05731'
        ]

        for code in codes:
            item = QStandardItem(code)
            item.setCheckable(True)
            self.model.appendRow(item)
        self.list.setModel(self.model)

    def filterClicked(self):
        filter_text = str(self.lineEdit.text()).lower()
        for row in range(self.model.rowCount()):
            if filter_text in str(self.model.item(row).text()).lower():
                self.list.setRowHidden(row, False)
            else:
                self.list.setRowHidden(row, True)

Upvotes: 5

Related Questions