Gtk4: GtkMessageDialog inherited?

I know that in Gtk4 many Widgets cannot be inherited including GtkMessageDialog. However, while playing around, I found that the code below work :

#pragma once

#include <gtk/gtk.h>

G_BEGIN_DECLS

#define DLG_TYPE_TEST            (dlg_test_get_type ())
G_DECLARE_FINAL_TYPE (DlgTest, dlg_test, DLG, TEST, GtkDialog)


GtkWidget  *dlg_test_new	  (GtkWindow *parent);

G_END_DECLS
#include "dlg-test.h"


struct _DlgTest {
  GtkMessageDialog parent;
};

G_DEFINE_TYPE (DlgTest, dlg_test, GTK_TYPE_MESSAGE_DIALOG);

static void
dlg_test_class_init (DlgTestClass *klass)
{
	GtkWidgetClass *widget_class = (GtkWidgetClass*) klass;

        gtk_widget_class_set_template_from_resource (widget_class,
						     "/ui/dlg-test.ui");
}

static void
dlg_test_init (DlgTest *self)
{
  gtk_widget_init_template (GTK_WIDGET (self));
}

GtkWidget *
dlg_test_new (GtkWindow *parent)
{
	return g_object_new (DLG_TYPE_TEST,
                             "transient-for", parent,
                             "modal", TRUE,
	                     NULL);
}
<interface>
  <requires lib="gtk" version="4.0"/>
  <template class="DlgTest" parent="GtkMessageDialog">
    <property name="text">This is a text</property>
    <property name="secondary-text">This is a secondary-text</property>
    <child type="action">
      <object class="GtkButton" id="button_cancel">
        <property name="label">CANCEL</property>
      </object>
    </child>
    <child type="action">
      <object class="GtkButton" id="button_ok">
        <property name="label">OK</property>
      </object>
    </child>
    <action-widgets>
      <action-widget response="cancel">button_cancel</action-widget>
      <action-widget response="ok" default="true">button_ok</action-widget>
    </action-widgets>
  </template>
</interface>

Please note, that the parentName in G_DECLARE_FINAL_TYPE is a GtkDialog while the parentType, the parent instance and the parent template are a GtkMessageDialog. Everything works fine without error and even GTK_IS_MESSAGE_DIALOG return TRUE.

And so I have two question:

  • How can it works ?
  • Is this something allowed to use in application code or it should not be ?

Thanks !

This is just an accident: GtkMessageDialog has the same size of GtkDialog, so you’re taking advantage of undefined behaviour.

Additionally, the “final” flag for GType has only been introduced in GLib 2.70; in the future, GtkBuilder will check if a type is final, and will error out if you’re trying to create a template that inherits from a final type.

Ah ! I see that makes senses now…

Thanks for the answer :smile:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.