简体   繁体   中英

How can I implement spreadsheet like filtering in Qt TableView?

I have an application that already read data and puts it in a TableView so it looks more or less like this:

在此处输入图片说明

I would like to add a spreadsheet like filter to eg filter out the orders from particular company ( without a regex/wildcard text input field for filtering).

How can this be done?

Use QSortFilterProxyModel

http://qt-project.org/doc/qt-4.8/qsortfilterproxymodel.html

You need to reimplement bool QSortFilterProxyModel::filterAcceptsRow( int sourceRow );

Without seeing your model I cannot give you exact details, but your reimplemented filter would look something like this:

class myFilter : public QSortFilterProxyModel
{
    Q_OBJECT
public:
    myFilter( QObject* parent = NULL );
    virtual ~myFilter();

    virtual bool filterAcceptsRow( int sourceRow ) 
    {
        const QAbstractTableModel* myModel = dynamic_cast<QAbstractTableModel*>( sourceModel() );
        if ( myModel->companyByRowOkay( sourceRow ) { 
            return true;
        }

        return false;

    }


private:
};

Setup is as follows:

QAbstractTableModel* Model = new QAbstractTableModel();
myFilter* Filter = new myFilter();
QTableView* View = new QTableView();

proxy->setSourceModel( Model );
view->setModel( proxy );

You get the idea. Generally the QSortFilterProxyModel sits between the model and the delegate, so if you ever talk to your model directly from the delegate, you need to keep this in mind, as the indexes will be different.

EDIT: Also read up on when to call invalidate() in the QSortFilterProxyModel, or you might pull your hair out.

http://qt-project.org/doc/qt-5/qtablewidget.html#sortItems

void QTableWidget::sortItems(int column, Qt::SortOrder order = Qt::AscendingOrder)

Sorts all the rows in the table widget based on column and order.

http://qt-project.org/doc/qt-5/qtsql-tablemodel-example.html

As for filtering, you probably need to come up with your own kind of pop up widget that can do filtering.

Maybe add a QContextMenu that goes and draws a list of checkboxes of a set of all the items it could find in that column. Look to see how Excel or LibreOffice Calc does it, and mimic the design.

And clicking a checkbox or clicking okay on the popup, does a quick run through all the rows and sets the row height to zero or hides the row, or hides all the QTableWidgetItem s in that row.

If you are backed by SQLite or MySQL or some other database, use the Table Model Example and do a new query if you want to filter it. (Assuming that you have a relatively small number of rows).

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM