代码之家  ›  专栏  ›  技术社区  ›  JokerMartini

使用pyside搜索qtableview中的所有行

  •  1
  • JokerMartini  · 技术社区  · 6 年前

    如何使用检查每行每列的每个显示角色值的搜索字符串筛选qtableview中的行?请记住,在这种情况下,可以根据复选框更改可见的列。同时保持通过单击列标题对行进行排序的能力。

    导入OS、sys、json、pprint sys.path.append(os.environ.get('ps_sitepackages')) 从qt导入qtgui、qtwidgets、qtcore 类QdictTableView(qtWidgets.qWidget): 定义初始化(self,*args,**kwargs): super(qdicttableview,self)。初始值(*args,**kwargs) 自我调整大小(400300) #控制 self.ui_search_input=qtwidgets.qlineedit()。 self.ui_search_input.setplaceholderText('search…') self.ui_name_filter=qtwidgets.qcheckbox('name') self.ui_age_filter=qtwidgets.qcheckbox('age') self.ui_career_filter=qtwidgets.qcheckbox('career') self.ui_item_table=qtWidgets.qtableView()。 self.ui_item_table.setEditTriggers(qtWidgets.qAbstratemView.NoEditTriggers) self.ui_item_table.setSelectionBehavior(qtWidgets.qabstratemView.selectRows) self.ui_item_table.verticalHeader().hide()) self.ui_item_table.setModel(qtgui.qStandardItemModel()) #敷设总管 lay_filters=qtwidgets.qhboxlayout()。 lay_filters.addwidget(self.ui_name_filter) lay_filters.addwidget(self.ui_age_filter) lay_filters.addwidget(self.ui_career_filter) lay_main=qtwidgets.qvboxlayout()。 放置主集合对齐(qtcore.qt.AlignTop) lay_main.addwidget(self.ui_search_输入) 布局主布局(布局过滤器) lay_main.addwidget(self.ui_item_table) 自设置布局(主布局) #连接 self.ui_search_input.textChanged.connect(self.changed_text) self.ui_name_filter.statechanged.connect(self.populate_table) self.ui_age_filter.stateChanged.connect(self.populate_table) self.ui_career_filter.statechanged.connect(self.populate_table) #正在 self.populate表格() self.ui_name_filter.setchecked(真) self.ui_age_filter.setchecked(真) self.ui_career_filter.setchecked(真) #方法 def更改了文本(self,text): print'搜索:',文本 def填充表格(self): 人=[ '姓名':'凯文','年龄':5,'职业':'运动员', 'name':'maggie','age':13,'career':'banker', 'name':'leslie','age':32,'career':'banker', '姓名':'艾米丽','年龄':45,'职业':'运动员', 'name':'david','age':27,'career':'banker', 'name':'marie','age':63,'career':'secretary' ] model=self.ui_item_table.model()。 模型.clear()) self.ui_item_table.setsortingabled(false) #列标题 标题=[] 如果self.ui_name_filter.ischecked(): headers.append('名称') 如果self.ui年龄过滤器.ischecked(): headers.append('年龄') 如果self.ui_career_filter.ischecked(): headers.append('职业') Model.setHorizontalHeaderLabels(标题) #model.setHeaderData(i,qt::horizontal,thermonames.at(i)); #填充行 对于X的人: 行=[] 如果self.ui_name_filter.ischecked(): col=qtgui.qstandarditem()。 col.setdata(x.get('name','na'),role=qtcore.qt.displayRole) col.setdata(x,role=qtcore.qt.userrole) 行附加(col) 如果self.ui年龄过滤器.ischecked(): col=qtgui.qstandarditem()。 col.setdata(x.get('age','na'),role=qtcore.qt.displayRole) col.setdata(x,role=qtcore.qt.userrole) 行附加(col) headers.append('年龄') 如果self.ui_career_filter.ischecked(): col=qtgui.qstandarditem()。 col.setdata(x.get('career','na'),role=qtcore.qt.displayRole) col.setdata(x,role=qtcore.qt.userrole) 行附加(col) headers.append('职业') Model.AppendRow(行) #之后更新用户界面 self.ui_item_table.setsortingabled(真) self.ui_item_table.sortByColumn(0,qtcore.qt.ascendingorder) 如果“名称”= app=qtwidgets.qapplication(系统argv) ex=qdicttableview()。 例如,show()) 系统退出(app.exec_u())

    enter image description here

    import os, sys, json, pprint
    sys.path.append(os.environ.get('PS_SITEPACKAGES'))
    from Qt import QtGui, QtWidgets, QtCore
    
    
    class QDictTableView(QtWidgets.QWidget):
    
        def __init__(self, *args, **kwargs):
            super(QDictTableView, self).__init__(*args, **kwargs)
            self.resize(400,300)
    
            # controls
            self.ui_search_input = QtWidgets.QLineEdit()
            self.ui_search_input.setPlaceholderText('Search...')
    
            self.ui_name_filter = QtWidgets.QCheckBox('Name')
            self.ui_age_filter = QtWidgets.QCheckBox('Age')
            self.ui_career_filter = QtWidgets.QCheckBox('Career')
    
            self.ui_item_table = QtWidgets.QTableView()
            self.ui_item_table.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
            self.ui_item_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
            self.ui_item_table.verticalHeader().hide()
            self.ui_item_table.setModel(QtGui.QStandardItemModel())
    
            # lay main
            lay_filters = QtWidgets.QHBoxLayout()
            lay_filters.addWidget(self.ui_name_filter)
            lay_filters.addWidget(self.ui_age_filter)
            lay_filters.addWidget(self.ui_career_filter)
    
            lay_main = QtWidgets.QVBoxLayout()
            lay_main.setAlignment(QtCore.Qt.AlignTop)
            lay_main.addWidget(self.ui_search_input)
            lay_main.addLayout(lay_filters)
            lay_main.addWidget(self.ui_item_table)
            self.setLayout(lay_main)
    
            # connections
            self.ui_search_input.textChanged.connect(self.changed_text)
            self.ui_name_filter.stateChanged.connect(self.populate_table)
            self.ui_age_filter.stateChanged.connect(self.populate_table)
            self.ui_career_filter.stateChanged.connect(self.populate_table)
    
            # being
            self.populate_table()
            self.ui_name_filter.setChecked(True)
            self.ui_age_filter.setChecked(True)
            self.ui_career_filter.setChecked(True)
    
    
        # methods
        def changed_text(self, text):
            print 'SEARCHING:', text
    
    
        def populate_table(self):
            people = [
                {'name': 'Kevin', 'age': 5, 'career': 'athlete'},
                {'name': 'Maggie', 'age': 13, 'career': 'banker'},
                {'name': 'Leslie', 'age': 32, 'career': 'banker'},
                {'name': 'Emily', 'age': 45, 'career': 'athlete'},
                {'name': 'David', 'age': 27, 'career': 'banker'},
                {'name': 'Marie', 'age': 63, 'career': 'secretary'}
            ]
    
            model = self.ui_item_table.model()
            model.clear()
            self.ui_item_table.setSortingEnabled(False)
    
            # column headers
            headers = []
            if self.ui_name_filter.isChecked():
                headers.append('Name')
            if self.ui_age_filter.isChecked():
                headers.append('Age')
            if self.ui_career_filter.isChecked():
                headers.append('Career')
            model.setHorizontalHeaderLabels(headers)
            # model.setHeaderData( i, Qt::Horizontal,thermoNames.at(i));
    
            # populate rows
            for x in people:
    
                row = []
    
                if self.ui_name_filter.isChecked():
                    col = QtGui.QStandardItem()
                    col.setData(x.get('name', 'NA'), role=QtCore.Qt.DisplayRole)
                    col.setData(x, role=QtCore.Qt.UserRole)
                    row.append(col)
    
                if self.ui_age_filter.isChecked():
                    col = QtGui.QStandardItem()
                    col.setData(x.get('age', 'NA'), role=QtCore.Qt.DisplayRole)
                    col.setData(x, role=QtCore.Qt.UserRole)
                    row.append(col)
                    headers.append('Age')
    
                if self.ui_career_filter.isChecked():
                    col = QtGui.QStandardItem()
                    col.setData(x.get('career', 'NA'), role=QtCore.Qt.DisplayRole)
                    col.setData(x, role=QtCore.Qt.UserRole)
                    row.append(col)
                    headers.append('Career')
    
                model.appendRow(row)
    
            # update ui after
            self.ui_item_table.setSortingEnabled(True)
            self.ui_item_table.sortByColumn(0, QtCore.Qt.AscendingOrder)
    
    
    
    if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
        ex = QDictTableView()
        ex.show()
        sys.exit(app.exec_())
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   eyllanesc RAHUL KUMAR    6 年前

    QSortFilterProxyModel filterAcceptsRow() setColumnHidden() QTableView

    import sys
    import os
    sys.path.append(os.environ.get('PS_SITEPACKAGES'))
    from Qt import QtGui, QtWidgets, QtCore
    
    from functools import partial
    
    
    class FilterProxy(QtCore.QSortFilterProxyModel):
        def __init__(self, *args, **kwargs):
            super(FilterProxy, self).__init__(*args, **kwargs)
            self.filters_colums = set()
            self.mText = ""
    
        def setText(self, text):
            self.mText = text
            self.invalidateFilter()
    
        def appendColumn(self, name):
            self.filters_colums.add(name.lower())
            self.invalidateFilter()
    
        def removeColumn(self, name):
            self.filters_colums.discard(name.lower())
            self.invalidateFilter()
    
        def filterAcceptsRow(self, source_row, source_parent):
            if self.mText:
                for i in range(self.sourceModel().columnCount()):
                    header = self.sourceModel().headerData(i, QtCore.Qt.Horizontal) 
                    text = self.sourceModel().index(source_row, i).data()
                    if header in self.filters_colums and self.mText in text.lower():
                        return True
                return False
            return True
    
    
    class QDictTableView(QtWidgets.QWidget):
        def __init__(self, *args, **kwargs):
            super(QDictTableView, self).__init__(*args, **kwargs)
            self.resize(400,300)
    
            # controls
            self.ui_search_input = QtWidgets.QLineEdit()
            self.ui_search_input.setPlaceholderText('Search...')
    
            self.ui_item_table = QtWidgets.QTableView()
            self.ui_item_table.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
            self.ui_item_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
            self.ui_item_table.verticalHeader().hide()
    
            lay_filters = QtWidgets.QHBoxLayout()
            lay_main = QtWidgets.QVBoxLayout(self)
            lay_main.setAlignment(QtCore.Qt.AlignTop)
            lay_main.addWidget(self.ui_search_input)
            lay_main.addLayout(lay_filters)
            lay_main.addWidget(self.ui_item_table)
    
            model = self.populate_table()
            self.proxy = FilterProxy()
            self.proxy.setSourceModel(model)
            self.ui_item_table.setModel(self.proxy)
    
            for text in ("Name", "Age", "Career"):
                checkbox = QtWidgets.QCheckBox(text)            
                checkbox.stateChanged.connect(partial(self.update_columns, text))
                checkbox.setChecked(True)
                lay_filters.addWidget(checkbox)
    
            self.ui_search_input.textChanged.connect(self.proxy.setText)
    
        def update_columns(self, text, state):
            cols = self.ui_item_table.model().columnCount()
            i = [self.ui_item_table.model().headerData(i, QtCore.Qt.Horizontal) for i in range(cols)].index(text.lower())
            self.ui_item_table.setColumnHidden(i, state == QtCore.Qt.Unchecked)
            if state == QtCore.Qt.Unchecked:
                self.proxy.removeColumn(text)
            else:
                self.proxy.appendColumn(text)
    
        def populate_table(self):
            peoples = [
                {'name': 'Kevin', 'age': 5, 'career': 'athlete'},
                {'name': 'Maggie', 'age': 13, 'career': 'banker'},
                {'name': 'Leslie', 'age': 32, 'career': 'banker'},
                {'name': 'Emily', 'age': 45, 'career': 'athlete'},
                {'name': 'David', 'age': 27, 'career': 'banker'},
                {'name': 'Marie', 'age': 63, 'career': 'secretary'}
            ]
    
            model = QtGui.QStandardItemModel()
    
            headers = ["name", "age", "career"]
            model.setHorizontalHeaderLabels(headers)
    
            for row, people in enumerate(peoples):
                items = []
                for key, value in people.items():
                    col = headers.index(key)
                    item = QtGui.QStandardItem(str(value))
                    items.append(item)
                model.insertRow(row, items)
            return model
    
    if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
        ex = QDictTableView()
        ex.show()
        sys.exit(app.exec_())