The FontChooserDialog
(deprecated since gtkmm 4.10) and
FontDialog
(available since gtkmm 4.10) allow the user
to choose a font. The FontButton
(deprecated since gtkmm 4.10)
and FontDialogButton
(available since gtkmm 4.10) open
a font chooser dialog when it is clicked.
File: examplewindow.h
(For use with gtkmm 4)
#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H
#include <gtkmm.h>
class ExampleWindow : public Gtk::Window
{
public:
ExampleWindow();
~ExampleWindow() override;
protected:
//Signal handlers:
void on_font_button_font_set();
void on_button_dialog_clicked();
void on_dialog_finish(const Glib::RefPtr<Gio::AsyncResult>& result);
//Child widgets:
Gtk::Box m_ButtonBox;
Gtk::FontDialogButton m_FontDialogButton;
Gtk::Button m_Button_Dialog;
Glib::RefPtr<Gtk::FontDialog> m_pDialog;
};
#endif //GTKMM_EXAMPLEWINDOW_H
File: examplewindow.cc
(For use with gtkmm 4)
#include "examplewindow.h"
#include <iostream>
ExampleWindow::ExampleWindow()
: m_ButtonBox(Gtk::Orientation::VERTICAL),
m_Button_Dialog("Choose Font")
{
set_title("Gtk::FontDialog example");
set_child(m_ButtonBox);
m_pDialog = Gtk::FontDialog::create();
m_ButtonBox.append(m_FontDialogButton);
m_FontDialogButton.set_dialog(m_pDialog);
m_FontDialogButton.set_font_desc(Pango::FontDescription("Sans 10"));
m_FontDialogButton.set_expand(true);
m_FontDialogButton.set_use_font(true);
m_FontDialogButton.set_use_size(true);
m_FontDialogButton.property_font_desc().signal_changed().connect(
sigc::mem_fun(*this, &ExampleWindow::on_font_button_font_set));
m_ButtonBox.append(m_Button_Dialog);
m_Button_Dialog.set_expand(true);
m_Button_Dialog.signal_clicked().connect(
sigc::mem_fun(*this, &ExampleWindow::on_button_dialog_clicked));
}
ExampleWindow::~ExampleWindow()
{
}
void ExampleWindow::on_font_button_font_set()
{
auto font_name = m_FontDialogButton.get_font_desc().to_string();
std::cout << "Font chosen: " << font_name << std::endl;
}
void ExampleWindow::on_button_dialog_clicked()
{
// Get the previously selected font description from the FontDialogButton.
m_pDialog->choose_font(*this,
sigc::mem_fun(*this, &ExampleWindow::on_dialog_finish),
m_FontDialogButton.get_font_desc());
}
void ExampleWindow::on_dialog_finish(const Glib::RefPtr<Gio::AsyncResult>& result)
{
try
{
// If this call changes the font, it will trigger a call to
// on_font_button_font_set().
m_FontDialogButton.set_font_desc(m_pDialog->choose_font_finish(result));
}
catch (const Gtk::DialogError& err)
{
// Can be thrown by m_pDialog->choose_font_finish(result).
std::cout << "No font selected. " << err.what() << std::endl;
}
catch (const Glib::Error& err)
{
std::cout << "Unexpected exception. " << err.what() << 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);
}