Overriding virtual methods in PyGObject

I am trying to implement Heigh-for-width Geometry Management in GTK with Python for my custom widget. My widget is a subclass of Gtk.DrawingArea and draws some parts of the image.

As I understand it, GTK Docs (link above), I have to implement the following 4 methods:

  • GtkWidgetClass.get_preferred_width ()
  • GtkWidgetClass.get_preferred_height ()
  • GtkWidgetClass.get_preferred_height_for_width ()
  • GtkWidgetClass.get_preferred_width_for_height ()

Now I wonder where to implement this in Python.

I tried this:

 from gi.repository import Gtk class Patch(Gtk.DrawingArea): def __init__(self, model, image, position): super(Patch,self).__init__() #… def get_preferred_width(self, *args, **kargs): print("test") def get_preferred_height(self, *args, **kargs): print("test") def get_preferred_width_for_height(self, *args, **kargs): print("test") def get_preferred_height_for_width(self, *args, **kargs): print("test") 

But methods are not called. In C, you define functions and set them for the widget as follows:

 static void my_widget_get_preferred_height (GtkWidget *widget, gint *minimal_height, gint *natural_height) { /* ... */ } /* ... */ static void my_widget_class_init (MyWidgetClass *class) { /* ... */ GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class); widget_class->get_preferred_height = my_widget_get_preferred_height; /* ... */ } 

How is this done in Python?

+3
source share
1 answer

You should name methods like do_virtual_method :

 from gi.repository import Gtk class Patch(Gtk.DrawingArea): def __init__(self): super(Patch,self).__init__() def do_get_preferred_width(self): print("test") return 100, 100 def do_get_preferred_height(self): print("test") return 100, 100 win = Gtk.Window() win.add(Patch()) win.connect('destroy', Gtk.main_quit) win.show_all() Gtk.main() 

Please note that you also need to return the values ​​that the virtual method needs to return, otherwise you will get a cryptic error.

+3
source

Source: https://habr.com/ru/post/1398594/


All Articles