Originally, I had a simple filter function that took the text from a QLineEdit and matched it with the text from all cells in a QTableWidget like this:
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
# ...
hlayout = QHBoxLayout()
fltrlbl = QLabel("Filter on: ")
hlayout.addWidget(fltrlbl)
self.fltrle = QLineEdit()
self.fltrle.textChanged.connect(self.filterer)
self.fltrle.setClearButtonEnabled(True)
hlayout.addWidget(self.fltrle)
# ...
def filterer(self, filtertext):
for i in range(self.table.rowCount()):
for j in range(self.table.columnCount()):
item = self.table.item(i, j).text()
match = filtertext.lower() not in item.lower()
self.table.setRowHidden(i, match)
if not match:
break
This worked perfectly, but users asked that they be able to specify which column the filter was applied to. So I added a QComboBox with a list of the columns and updated the code as follows:
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
# ...
hlayout = QHBoxLayout()
fltrlbl = QLabel("Filter on: ")
hlayout.addWidget(fltrlbl)
self.fltrcb = QComboBox()
self.fltrcb.addItems(["Name", "Email", "Address",
"City", "State", "Zip"])
hlayout.addWidget(self.fltrcb)
self.fltrle = QLineEdit()
self.fltrle.textChanged.connect(self.filterer)
self.fltrle.setClearButtonEnabled(True)
hlayout.addWidget(self.fltrle)
# ...
def filterer(self, filtertext):
icol = self.fltrcb.currentIndex()
for irow in range(self.table.rowCount()):
item = self.table.item(irow, icol).text()
match = filtertext.lower() not in item.lower()
self.table.setRowHidden(irow, match)
if not match:
break
Now, the filterer function stops after 1 iteration. For example, lets say there are 100 rows. If I search for "John Smith", and "John Smith" is in row 12, then rows 12 through 100 will be displayed instead of just row 12. Then, when I clear the QLineEdit, only row 1 comes back (so rows 1 and 12 through 100 are displayed).
Thanks in advance.