I am trying out the basic QSortFilterProxyModel example in qt assistant and have made a QSqlTableModel to try and filter.The example i have made is not filtering as it is should and i need assistance to know why.
/*
ned.h
*/
#ifndef NED_H
#define NED_H
#include <QWidget>
#include <QtSql>
#include "ui_ned.h"
class QSortFilterProxyModel;
class ned : public QWidget
{
Q_OBJECT
public:
ned(QWidget *parent = 0);
private:
void setupModel();
QSortFilterProxyModel *proxyModel;
QSqlTableModel *tableModel;
Ui::ned ui;
private slots:
void filterRegExpChanged();
};
#endif // NED_H
.........................................................开发者_如何学运维........
.................................................................
/*
ned.cpp
*/
#include <QtGui>
#include <QtSql>
#include <QwwClearLineEdit>
#include "ned.h"
ned::ned(QWidget *parent) :
QWidget(parent)
{
ui.setupUi(this);
setupModel();
tableModel = new QSqlTableModel(ui.tableView);
tableModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
tableModel->setTable("tables");
ui.tableView->setModel(tableModel);
ui.tableView->setColumnHidden(tableModel->fieldIndex("id"), true);
ui.tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui.tableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui.tableView->setAlternatingRowColors(true);
ui.tableView->setSortingEnabled(true);
ui.tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui.tableView->horizontalHeader()->setStretchLastSection(true);
proxyModel = new QSortFilterProxyModel;
proxyModel->setDynamicSortFilter(true);
proxyModel->setSourceModel(tableModel);
proxyModel->setFilterKeyColumn(1);
tableModel->select();
//Locale
tableModel->setHeaderData(1, Qt::Horizontal, tr("Table Name"));
tableModel->setHeaderData(2, Qt::Horizontal, tr("Table Description"));
connect(ui.nedsort, SIGNAL(textChanged(QString)),
this, SLOT(filterRegExpChanged()),Qt::UniqueConnection);
}
void ned::setupModel()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("smith.DAT");
if (!db.open())
{
QMessageBox::critical(0, tr("Cannot open database"),
tr("Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information how "
"to build it."), QMessageBox::Cancel);
return;
}
}
void ned::filterRegExpChanged()
{
QRegExp regExp(ui.nedsort->text());
proxyModel->setFilterRegExp(regExp);
}
This line is wrong:
ui.tableView->setModel(tableModel);
You have to set the model to the proymodel (later):
ui.tableView->setModel(proxyModel);
精彩评论