为QListView中显示的项创建QLineEdit搜索字段

jky*_*yle 6 c++ qt4

我想创建一个搜索字段来过滤QListView中显示的项目.基本上用户可以输入"foo",只显示DisplayRole中带有"foo"的项目.

我已经有一些关于如何做到这一点的想法,但我想我会问那些比我更有经验的人.

我的想法是使用一些信号和插槽在QAbstractItem模型中设置过滤器并在QListView中触发update().

QListView中是否有任何帮助方法可用于过滤我可能错过了?

有没有一种规范的处理方法,我还没有遇到过?

编辑

目前的进展.

我在我的QFileSystemModel子类中创建了一个名为"updateFilter(QString)"的公共插槽.然后我

connect(myQLineEditSearch, SIGNAL(textChanged(QString)), 
        myQFileSysModel, SLOT(updateFilter(QString)));
Run Code Online (Sandbox Code Playgroud)

这设置了过滤器,然后在我的QFileSystemModel :: data(...)方法中,我有:

  void ComponentModel::updateFilter(QString filter)
  {
    _filter = filter;
    emit layoutChanged();
  }

  QVariant ComponentModel::data(const QModelIndex &index, int role) const
  {
    QVariant result;

    // if our search filter term is set and the item does not match,
    // do not display item data. Searches are case insensitive
    if (!_filter.isEmpty() &&
        !QFileSystemModel::data(index, Qt::DisplayRole)
        .toString().toLower().contains(_filter.toLower()))
    {
      return result;
    }

    result = QFileSystemModel::data(index, role);
    return result;
  }
Run Code Online (Sandbox Code Playgroud)

这几乎就在那里.我正在研究的"故障"与对象的显示位置有关.目前,如果我应用与列表中第3项匹配的搜索,则前两行将呈现为空白.换句话说,它仍然为非匹配项呈现行.

jky*_*yle 6

回答我自己的问题以供参考.

看起来这里需要的是QSortFilterProxyModel.

代码看起来像:

QListView *myview = new QListView(this);
MyModel *model = new MyModel(this);
QSortFilterProxyModel *proxy = new QSortFilterProxyModel(this);

proxy->setSourceModel(model);
myview->setModel(proxy);

myview->setRootIndex(proxy->mapFromSource(model->index(model->rootPath()));

connect(filterLineEdit, SIGNAL(textChanged(QString)), 
        proxy,          SLOT(setFilterFixedString(QString)));
Run Code Online (Sandbox Code Playgroud)

我在这里看到的唯一问题是当你输入搜索字符串时,rootIndex似乎被重置.当我弄明白时,我会更新.