带有QSqlTableModel的QSortFilterProxyModel

时间:2011-10-06 17:53:08

标签: qt qt4

我正在尝试qt助手中的基本QSortFilterProxyModel示例并且已经使QSqlTableModel尝试并过滤。我所做的示例不是过滤,因为它应该是我需要帮助才能知道原因。

/*
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);
}

1 个答案:

答案 0 :(得分:2)

这一行错了:

 ui.tableView->setModel(tableModel);

您必须将模型设置为预模型(稍后):

 ui.tableView->setModel(proxyModel);