13.3.3.  Sorting and Filtering

[ fromfile: tablemodels.xml id: sortfilter ]

Figure 13.10.  Filtered Table View

Filtered Table View

Don't bother looking for the code creating the QLineEdit, the clear button, or the connect between the two in Figure 13.10. Those were all defined in Designer and generated by uic.

Thanks to QSortFilterProxyModel, you can add sorting/filtering capability to an existing model with fewer than five lines of code. Figure 13.11 shows how the proxy sits between the view and the model.

Figure 13.11.  Sort Filter Proxy

Sort Filter Proxy

Example 13.20 shows what is needed to set up the sort filter proxy in the preceding action table example.

Example 13.20. src/libs/actioneditor/actiontableeditor.cpp

[ . . . . ]

void ActionTableEditor::setupSortFilter() {
    m_sortFilterProxy = new QSortFilterProxyModel(this);
    m_sortFilterProxy->setSourceModel(m_model);       1
    m_ui->m_tableView->setModel(m_sortFilterProxy);   2    
    m_sortFilterProxy->setFilterKeyColumn(-1);        3

}
void ActionTableEditor::on_m_filterField_textChanged  4  
    (const QString& newText) { 
    m_sortFilterProxy->setFilterFixedString(newText); 5
}

1

SortFilterProxy source model set to ActionTableModel.

2

Table view model set to proxy model instead of ActionTableModel.

3

Filter on all fields.

4

Auto-connected slot.

5

Change the filter string.

<include segid="sortfilter" mode="cpp" href="src/libs/actioneditor/actiontableeditor.cpp" id="sortfilter-setup-cpp" src="src/libs/actioneditor/actiontableeditor.cpp"/>


The filterField_textChanged is an auto-connected slot that gets called whenever the textChanged signal is emitted by the filterField QLineEdit.