Important: Please read the Qt Code of Conduct -


  • Hi,

    I am trying to implement a custom filter model for my QTableView. My QTableView has a model which implements QAbstractTableModel.
    My QTableView contains columns with string values and columns with double values.

    Some background :
    Originally I was using QTableWidget since I did not really had to do anything with the data. Then I changed that to QTableView to implement sorting based on double values instead of considering then as string and sorting. [Note: I tried QVariant setData display double values. It did not work ]. So then I took the QTableView route since I wanted to filtering of the table as well.

    I have implemented a custom model using QAbstractTableModel. I have reimplemented rowCount, columnCount, data, headerData and sort. The sorting works fine on the header click which calls the sort of my custom model.

    I am stuck at how to implement the custom filter. Something like Excel for the double values.

    For egs. For the selected column :
    1 Filter rows that does not have value greater than or equal to 6.705
    2.Filter rows that has values between 1.607 to 5.341
    3.Filter rows that has values less than 4.5 and similar.

    I created a source Model and implemented QSortFilterProxyModel. I read that to implement custom filter I should re implement filterAcceptRows function and set the setFilterRegExp. Since I have to compare numeric value I feel little unsure with this approach. Also how can I inform the setAcceptRows about my column index.

    Should I use the filterKeyColumn property? But then my data model can have data of more than 10,000 rows. Do I have to loop through each row and call filterAcceptRows to show or hide the rows ?

    Can someone please shine some light on the direction I am taking and is there a better alternative and QSortFilterProxyModel is an overkill ?

    Thanks in advance.

    1. Possibly, "Custom Sort/Filter Example" from Qt docs will help you.
    2. You can use setFilterFixedString() method from QSortFilterProxyModel to setup custom filter string than override lessThan(), filterAcceptsRow() methods.

  • You can add your own methods to your sort filter proxy model subclass. Those can take the double values as you need them, eg.

    setFilterGreaterThanOrEqual(double lowerBound);
    setFilterRange(double lowerBound, double upperBound);

    and so on. Internally you can set a state variable that determines which comparisons to execute.

    Then you need to reimplement filterAcceptsRow() accordingly. The setFilterXXX can be used, but are ignored in your case.

Log in to reply