简体   繁体   English

QTableView实时过滤

[英]QTableView real-time filtering

My situation looks like this: I have QTableView and LineEdit. 我的情况看起来像这样:我有QTableView和LineEdit。 I'd like to show data which contains value in LineEdit in real time. 我想实时显示LineEdit中包含值的数据。 I guess I should use QSortProxyFilterModel, but I don't know how to do that. 我想我应该使用QSortProxyFilterModel,但是我不知道该怎么做。 I wrote this: 我这样写:

void MainWindow::on_lineFind_textEdited(const QString &arg1)
{

QSortFilterProxyModel proxy;
proxy.setSourceModel(ui->tableView->model());
proxy.setFilterRegExp(arg1);
QModelIndex index=proxy.mapToSource(proxy.index(0,0));
if(index.isValid())
  {
    ui->tableView->selectionModel()->select(index,QItemSelectionModel::Select | QItemSelectionModel::Rows);
    ui->tableView->scrollTo(index,QAbstractItemView::EnsureVisible);
  }


}

But it doesn't work (no change visible). 但这是行不通的(看不到任何变化)。 Example how it should work: Clementine Player playlist. 示例其工作方式:Clementine Player播放列表。

You create QSortFilterProxyModel and destroy it immediately in your function. 您创建QSortFilterProxyModel并立即在函数中销毁它。 It's incorrect use. 使用不正确。 You need to create one object of QSortFilterProxyModel (maybe using new ), then call QTableView::setModel for attaching proxy model to your view. 您需要创建一个QSortFilterProxyModel对象(也许使用new ),然后调用QTableView::setModel将代理模型附加到视图。 After that changes will take effect. 之后,更改将生效。

In the initialization: 在初始化中:

ui->setupUi(this);
my_model = new QStandardItemModel(); // or any other model class
proxy_model = new QSortFilterProxyModel();
ui->table_view->setModel(proxy_model);
proxy_model->setSourceModel(my_model);

In textEdited slot: 在textEdited插槽中:

proxy_model->setFilterRegExp(arg1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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