Connect ComboBox index with QSortFilterProxyModel
-
Hello,
I'm using Pyside2 and Python 3.8.
I have ComboBox1 where there's a list of all my columns, and Combobox2 where there's a list of all the distinct values in the ComboBox1's column. Each time the Combobox1 index changes, it emits a signal so that the list of items in ComboBox2 gets updated. I'm using two different QStringListModel for this.
The Comboboxs are initialized with the item "None", when None is selected, there's no filtering applied (displays all the rows)
What I'm trying to do is get to filter my QTableView from the two ComboBoxs. Each time the value in Combobox2 changes, the content of MyTableView changes according to the new filter.
I subclassed a proxyModel from QSortFilterProxyModel. I've tried my ProxyModel with several Filter Key Columns, and different data, it works, but when I try to dynamically filter the table, it doesn't work. Here's my code, if anyone can point out to me where I'm messing this up.Thanks.
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, parent=None): ProxyModel = ProxyModel() TableModel = TableModel() ProxyModel.setSourceModel(TableModel) TableModel.setModel(ProxyModel) self.ComboBox1.currentIndexChanged[str].connect(self.UpdateCombobox2) self.ComboBox1.currentIndexChanged[str].connect(self.MyTableView.model().setFilterColumn) self.Combobox2.currentIndexChanged[str].connect(self.MyTableView.model().Filtre) class ProxyModel(QtCore.QSortFilterProxyModel): def __init__(self,parent=None): super(ProxyModel, self).__init__() self._filter = "None" def setFilterColumn(self, header): if header == "None": return True for col in range(self.sourceModel().columnCount()): if self.sourceModel().headerData(col) == header: self.setFilterKeyColumn(col) return True return False def Filtre(self, valeur): self._filter = str(valeur) def filterAcceptsRow(self, sourceRow, sourceParent): if self._filter == "None": return False sourceModel = self.sourceModel() id = sourceModel.index(sourceRow, self.filterKeyColumn(), sourceParent) if sourceModel.data(id) == self._filter: return True return False
-
Hi,
You should invalidate the proxy model when you call Filtre.