Simple String Example

Figure 12.1. Simple DropDown

Simple DropDown

Source Code

File: examplewindow.h (For use with gtkmm 4)

#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include <gtkmm/window.h>
#include <gtkmm/dropdown.h>
#include <gtkmm/stringlist.h>

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();
  ~ExampleWindow() override;

protected:
  // Signal handler:
  void on_dropdown_changed();

  // Child widget:
  Gtk::DropDown m_DropDown;

  Glib::RefPtr<Gtk::StringList> m_StringList;
};

#endif //GTKMM_EXAMPLEWINDOW_H

File: examplewindow.cc (For use with gtkmm 4)

#include "examplewindow.h"
#include <iostream>

ExampleWindow::ExampleWindow()
{
  set_title("DropDown example");

  set_child(m_DropDown);

  // Fill the dropdown:
  const std::vector<Glib::ustring> strings{
    "1 minute", "2 minutes", "5 minutes", "20 minutes"
  };
  m_StringList = Gtk::StringList::create(strings);
  m_DropDown.set_model(m_StringList);
  m_DropDown.set_selected(0);

  // Connect signal handler:
  m_DropDown.property_selected().signal_changed().connect(
    sigc::mem_fun(*this, &ExampleWindow::on_dropdown_changed));
}

ExampleWindow::~ExampleWindow()
{
}

void ExampleWindow::on_dropdown_changed()
{
  const auto selected = m_DropDown.get_selected();
  std::cout << "DropDown changed: Row=" << selected
    << ", String=" << m_StringList->get_string(selected) << std::endl;
}

File: main.cc (For use with gtkmm 4)

#include "examplewindow.h"
#include <gtkmm/application.h>

int main(int argc, char* argv[])
{
  auto app = Gtk::Application::create("org.gtkmm.example");

  // Shows the window and returns when it is closed.
  return app->make_window_and_run<ExampleWindow>(argc, argv);
}