answerSeeker
answerSeeker

Reputation: 2772

How can I have a searchable Qlistview in pyqt

I have a QListView which displays a list of items using PyQt in Python. How can I get it to return a qlistview specific item when searched for?

For example, if I have the following Qlistview with 4 items, how can I get the item which contains text = dan? or bring it to the top of the list. Also, the search doesn't need to be completely specific, If I type "da" I'd like it to return dan or items that starts with "da" and possibly bring it to the top of the list

QListWidget

My Qlistview is defined as follows:

from PyQt4 import QtCore, QtGui
import os
import sys

class AppView(QtGui.QDialog):

    def __init__(self, parent=None):
        super(AppView, self).__init__(parent)
        self.resize(400, 400)
        self.ShowItemsList()

    def ShowItemsList(self):
        self.setWindowTitle("List")
        buttonBox = QtGui.QDialogButtonBox(self)
        buttonBox.setOrientation(QtCore.Qt.Horizontal)
        buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok)
        listview = QtGui.QListView(self)

        verticalLayout = QtGui.QVBoxLayout(self)
        verticalLayout.addWidget(listview)
        verticalLayout.addWidget(buttonBox)
        buttonBox.accepted.connect(self.close)
        model = QtGui.QStandardItemModel(listview)
        with open("names-list.txt") as input:
            if input is not None:
                item = input.readlines()
            for line in item:
                item = QtGui.QStandardItem(line)
                item.setCheckable(True)
                item.setCheckState(QtCore.Qt.PartiallyChecked)
                model.appendRow(item)

        listview.setModel(model)
        listview.show()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    view = AppView()
    view.show()
    sys.exit(app.exec_())

Upvotes: 1

Views: 2216

Answers (1)

answerSeeker
answerSeeker

Reputation: 2772

I fixed it like this. I made my model an instance variable beginning with self so that I can access it from another function.

def searchItem(self):
    search_string = self.searchEditText.text() # Created a QlineEdit to input search strings
    items = self.model.findItems(search_string, QtCore.Qt.MatchStartsWith)
    if len(items) > 0:
        for item in items:
            if search_string:
                self.model.takeRow(item.row()) #take row of item
                self.model.insertRow(0, item)  # and bring it to the top
    else:
        print "not found"

Upvotes: 4

Related Questions