Qt工作笔记-使用setFilterKeyColumn实现model的单行过滤

目录

 

原理

例子


 

原理

例子

程序运行截图如下:

 

源码如下:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

QT_BEGIN_NAMESPACE
class QStandardItemModel;
class QSortFilterProxyModel;
QT_END_NAMESPACE

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

protected slots:
    void col1LineEditChanged(const QString text);

private:
    Ui::Widget *ui;
    QStandardItemModel *m_model;
    QSortFilterProxyModel *m_filterModel;
};

#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QStandardItemModel>
#include <QRegExp>
#include <QDebug>
#include <QSortFilterProxyModel>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowTitle("CSDN IT1995");
    m_model = new QStandardItemModel;
    m_filterModel = new QSortFilterProxyModel;
    QStringList headList;
    headList << "第一列" << "第二列" << "第三列" << "第四列";
    m_model->setHorizontalHeaderLabels(headList);

    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);

    for(int row = 0; row < 100; row++){

        for(int col = 0; col < 4; col++){

            QStandardItem *newItem = new QStandardItem("第" + QString::number(row) + "行,第" + QString::number(col) + "列");
            newItem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
            m_model->setItem(row, col, newItem);
        }
    }

    connect(ui->colOneLineEdit,SIGNAL(textEdited(QString)), this, SLOT(col1LineEditChanged(QString)));

    m_filterModel->setSourceModel(m_model);
    ui->tableView->setModel(m_filterModel);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::col1LineEditChanged(const QString text)
{
    QRegExp rx(text);
    m_filterModel->setFilterKeyColumn(1);
    m_filterModel->setFilterRegExp(rx);
}

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

 

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页