Lägga till en sökrad

We continue to flesh out the functionality of our application. For now, we add search. gtkmm supports this with Gtk::SearchEntry and Gtk::SearchBar. The search bar is a widget that can slide in from the top to present a search entry.

We add a toggle button to the header bar, which can be used to slide out the search bar below the header bar. The new widgets are added in the window.ui file.

Implementing the search needs quite a few code changes that we are not going to completely go over here. The central piece of the search implementation is a signal handler that listens for text changes in the search entry, shown here without error handling.

void ExampleAppWindow::on_search_text_changed()
{
  const auto text = m_searchentry->get_text();
  auto tab = dynamic_cast<Gtk::ScrolledWindow*>(m_stack->get_visible_child());
  auto view = dynamic_cast<Gtk::TextView*>(tab->get_child());

  // Väldigt enkel sökimplementation.
  auto buffer = view->get_buffer();
  Gtk::TextIter match_start;
  Gtk::TextIter match_end;
  if (buffer->begin().forward_search(text, Gtk::TextSearchFlags::CASE_INSENSITIVE,
      match_start, match_end))
  {
    buffer->select_range(match_start, match_end);
    view->scroll_to(match_start);
  }
}

Med sökraden ser vårt program nu ut så här:

Lägga till en sökrad

Källkod