QTableview从过滤模型中选择项目

时间:2018-08-09 14:56:41

标签: python pyside qtableview qstandarditemmodel

我有一个使用QStandardItemModel的QTableView。如何在有/无搜索的情况下选择表格中的特定行。 例如,我在搜索栏中键入“ y”以过滤列表,以仅显示包含字母“ y”的行。当我单击“选择Emily”按钮时,考虑到用户可以更改排序顺序,如何使其在表格视图中选择正确的行? 导入系统 从PySide导入QtCore,QtGui 类示例(QtGui.QWidget):     def __init __(self,* args,** kwargs):         超级(示例,自我).__ init __(* args,** kwargs)         self.resize(400,400)         #控件         模型= QtGui.QStandardItemModel(5,3)         model.setHorizo​​ntalHeaderLabels(['NAME','AGE','CAREER'])         人= [             {'name':'Kevin','age':5,'career':'athlete'},             {'name':'Maggie','age':13,'career':'banker'},             {'name':'Leslie','age':32,'career':'banker'},             {'name':'Abby','age':32,'career':'marketing'},             {'name':'Emily','age':45,'career':'athlete'},             {'name':'David','age':27,'career':'banker'},             {'name':'Johnny','age':27,'career':'soccer'},             {'name':'Marie','age':63,'career':'secretary'}         ]         对于行,枚举中的obj(people):             item = QtGui.QStandardItem(obj ['name'])             model.setItem(row,0,item)             item = QtGui.QStandardItem(str(obj ['age']))             model.setItem(row,1,item)             item = QtGui.QStandardItem(obj ['career'])             model.setItem(row,2,item)         proxy_model = QtGui.QSortFilterProxyModel()         proxy_model.setSourceModel(模型)         #控件         self.ui_table = QtGui.QTableView()         self.ui_table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)         self.ui_table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)         self.ui_table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)         self.ui_table.setModel(proxy_model)         self.ui_table.setSortingEnabled(False)         self.ui_table.setSortingEnabled(真)         self.ui_table.sortByColumn(0,self.ui_table.horizo​​ntalHeader()。sortIndicatorOrder())         self.ui_search = QtGui.QLineEdit()         self.ui_selected = QtGui.QPushButton('选择艾蜜莉')         #主要         lay_main = QtGui.QVBoxLayout()         lay_main.addWidget(self.ui_search)         lay_main.addWidget(self.ui_table)         lay_main.addWidget(self.ui_selected)         self.setLayout(lay_main)         #个连接         self.ui_selected.clicked.connect(self.clicked_selected_emily)         self.ui_search.textChanged.connect(self.filter_items)     def clicked_selected_emily(自己):         打印“选择艾米丽”         self.ui_table.selectRow(2)     def filter_items(self,text):         行= self.ui_table.model()。rowCount()         对于范围(行)中的行:             self.filter_row(行,文本)     def filter_row(self,row,pattern):         如果不是模式:             self.ui_table.setRowHidden(row,False)             返回         模型= self.ui_table.model()         列= model.columnCount()         字符串列表= []         #将所有列中的文本收集到单个字符串中以进行搜索         对于范围内的c(列):             mdx = model.index(row,c)             如果mdx.isValid():                 val = str(mdx.data(role = QtCore.Qt.DisplayRole))。lower()                 stringlist.append(val)         #搜索字符串         pattern = filter(无,[pattern.split('')中[x的x.lower()])         结果=全部(对于模式中的x,任何(对于字符串列表中的y,x中的y中的x)         如果结果:             self.ui_table.setRowHidden(row,False)         其他:             self.ui_table.setRowHidden(row,True) 如果__name__ =='__main__':     应用= QtGui.QApplication(sys.argv)     例如= Example()     例如show()     sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

您必须使用模型的match()方法:

def clicked_selected_emily(self):
    print("select emily")
    self.ui_table.clearSelection()
    indexes = self.ui_table.model().match(
        self.ui_table.model().index(0, 0),
        QtCore.Qt.DisplayRole, # role of the search, the text uses the role Qt::DisplayRole
        "Emily", # value that is being searched in the model.
        -1, # maximum number of values ​​are being searched, if it is -1 it will search for all the matches
        QtCore.Qt.MatchExactly # type of search
    )
    for ix in indexes:
        self.ui_table.selectRow(ix.row())

更新

默认情况下,搜索是在上一示例中传递给self.ui_table.model().index(0, col)的列,如果要搜索所有列,则只应对其进行迭代以观察效果,​​从而启用了多选:

    self.ui_table.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)

...

def clicked_selected_emily(self):
    print("select banker")
    self.ui_table.clearSelection()
    word = "banker"

    for i in range(self.ui_table.model().columnCount()):
        indexes = self.ui_table.model().match(
            self.ui_table.model().index(0, i),
            QtCore.Qt.DisplayRole, # role of the search, the text uses the role Qt::DisplayRole
            "banker", # value that is being searched in the model.
            -1, # maximum number of values ​​are being searched, if it is -1 it will search for all the matches
            QtCore.Qt.MatchExactly # type of search
        )
        for ix in indexes:
            self.ui_table.selectRow(ix.row())

enter image description here