PyQt4 filter by text on a QListView using setRowHidden

烈酒焚心 提交于 2021-02-16 15:09:25

问题


I have a dialog which looks like this:

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?


回答1:


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)


来源:https://stackoverflow.com/questions/43667782/pyqt4-filter-by-text-on-a-qlistview-using-setrowhidden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!