I am trying to filter out items in a table based on string matching.
I have a QTableView displaying a Proxy Model to allow for filtering, however if an item in (0,0) and in (1,1) matches my string but item (1,0) doesn't, it will still be displayed.
For example:
from PySide.QtGui import *
from PySide.QtCore import *
class CustomProxyFilter(QSortFilterProxyModel):
def __init__(self):
super(CustomProxyFilter, self).__init__()
def filterAcceptsColumn(self, source_column, parent):
"""Re-implementing built-in to hide columns with non matches."""
model = self.sourceModel()
matched_string = self.filterRegExp().pattern().lower()
for row in range(model.rowCount()):
item = model.item(row, source_column)
if item and matched_string in model.item(row, source_column).text().lower():
return True
return False
class CustomTableView(QTableView):
"""Table view."""
def __init__(self, line_edit):
super(CustomTableView, self).__init__()
custom_model = StandardTableModel()
items = ["apple", "banana", "applebanana"]
for i, item in enumerate(items):
for v, second_item in enumerate(items):
custom_model.setItem(i, v, QStandardItem(item))
self.proxy_model = CustomProxyFilter()
self.proxy_model.setSourceModel(custom_model)
self.setModel(self.proxy_model)
line_edit.textChanged.connect(self.proxy_model.setFilterRegExp)
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.setLayout(QVBoxLayout())
self.line_edit = QLineEdit()
self.layout().addWidget(self.line_edit)
self.layout().addWidget(CustomTableView(self.line_edit))
What I am hoping would happen is if my table looks like
a|b|c
-----
c|a|b
The resulting table after filtering by "a" would be
a|a
My current solve shows.
a|b
---
c|a
Update for additional cases
a|a|c
-----
a|x|b
-----
c|b|a
becomes
a|a|a
-----
a
This case
a|a|y|c
-------
a|a|w|a
-------
c|a|w|w
Becomes
a|a|a|a
-----
a|a|
Essentially each item would move towards the top left when able. When they are different names, they would arrange themselves in alphabetical order like this
1|2|3|4
-------
5|6|7|8