python - PyQt4 使用 setRowHidden 在 QListView 上按文本进行过滤

标签 python pyqt pyqt4 qlineedit qlistview

我有一个如下所示的对话框:

enter image description here

该对话框具有连接到过滤器按钮的以下代码:

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)

但是,当我单击“过滤器”时,没有任何反应。我错过了什么?

最佳答案

问题是您隐藏了错误的项目。我已经展示了一个示例来展示解决方案。

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)

关于python - PyQt4 使用 setRowHidden 在 QListView 上按文本进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43667782/

相关文章:

Python Regex - 匹配一个字符而不消耗它

python - Tkinter tkMessageBox 禁用 Tkinter 键绑定(bind)

python - 如何在 QTableWidget 中使用过滤选项

python - PyQt4字符编码: 'ascii' codec can't encode character

python - Matplotlib - axvspan 与子图

python - 从控制台上的 PyQt5 浏览器中删除日志

python - 如何连接Qtoolbutton和QStackedWidget(两者都在同一框架中)

pyqt - QTableView/QTableWidget : Stretch Last Column using Qt Designer

python - PyQt4:为什么我们需要在调用 super() 时传递类名

python - 为什么我得到 pymongo.errors.AutoReconnect : connection pool paused