重写 PyGObject 中的虚拟方法

tho*_*ink 6 python gtk virtual-functions pygobject

我正在尝试使用 GTK 中的 Python 为我的自定义小部件实现高宽几何管理。我的小部件是图像的子类Gtk.DrawingArea,并绘制图像的某些部分。

\n\n

据我了解 GTK 文档(上面的链接),我必须实现以下 4 种方法:

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

现在想知道在Python 中哪里实现这个。

\n\n

我试过这个:

\n\n
from gi.repository import Gtk\nclass Patch(Gtk.DrawingArea):\n  def __init__(self, model, image, position):\n    super(Patch,self).__init__()\n    #\xe2\x80\xa6\n\n  def get_preferred_width(self, *args, **kargs):\n    print("test")\n\n  def get_preferred_height(self, *args, **kargs):\n    print("test")\n\n  def get_preferred_width_for_height(self, *args, **kargs):\n    print("test")\n\n  def get_preferred_height_for_width(self, *args, **kargs):\n    print("test")\n
Run Code Online (Sandbox Code Playgroud)\n\n

但这些方法不会被调用。在 C 中,您定义函数并将其设置为小部件,如下所示:

\n\n
static void\nmy_widget_get_preferred_height (GtkWidget *widget, gint *minimal_height,\n                                gint *natural_height)\n{\n  /* ... */\n}\n  /* ... */\n\nstatic void\nmy_widget_class_init (MyWidgetClass *class)\n{\n  /* ... */\n  GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);\n  widget_class->get_preferred_height = my_widget_get_preferred_height;\n  /* ... */\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是如何在 Python 中完成的?

\n

pto*_*ato 7

您必须将这些方法命名为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()
Run Code Online (Sandbox Code Playgroud)

请注意,您还必须返回虚拟方法要求您返回的值,否则您将收到一个神秘的错误。