2017-02-21 61 views
0

我有一個QListView,它顯示使用PyQt的項目列表,其中Python。如何在搜索時返回qlistview特定項目?如何在pyqt中搜索Qlistview

例如,如果我有以下Qlistview 4個項目,我如何獲得包含文本=丹的項目?或將其帶到列表的頂部。此外,搜索並不需要完全特定,如果我輸入「da」,我希望它返回丹或以「da」開頭並可能將其帶到列表頂部的項目

我而QListView定義如下:

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_()) 

回答

0

我固定它這樣。我讓我的模型成爲一個以自身開始的實例變量,以便我可以從另一個函數訪問它。

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"