从 Gtk.Widget 派生还是直接从特定小部件派生更好?

Is it better to derive from Gtk.Widget or directly from a specific widget?

当我为我的应用程序创建 UI class 时,我经常想知道从 Gtk.Widget 派生我的 class 然后显式添加我的小部件是否更好需要或直接从特定小部件派生。

这里有两个例子,哪个最好?

class MyComponent(Gtk.Widget):
    def __init__(self):
        Gtk.Widget.__init__(self)

        box = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 6)
        button1 = Gtk.Button.new_with_label("Awesome Button1")
        button2 = Gtk.Button.new_with_label("Awesome Button2")
        button3 = Gtk.Button.new_with_label("Awesome Button3")
        box.pack_start(button1, True, True, 0)
        box.pack_start(button2, True, True, 0)
        box.pack_start(button3, True, True, 0)

        self.add(box)
class MyComponent(Gtk.Box):
    def __init__(self):
        Gtk.Box.__init__(self, Gtk.Orientation.HORIZONTAL, 6)

        button1 = Gtk.Button.new_with_label("Awesome Button1")
        button2 = Gtk.Button.new_with_label("Awesome Button2")
        button3 = Gtk.Button.new_with_label("Awesome Button3")
        self.pack_start(button1, True, True, 0)
        self.pack_start(button2, True, True, 0)
        self.pack_start(button3, True, True, 0)

在我看来,第一个版本更好,因为我的组件在技术上不是 Gtk.Box,它是一个使用 Gtk.Box 的小部件,但它也可以使用 Gtk.GridGtk.DrawingArea.

从设计的角度来看,这似乎是正确的,但也许有一些我没有看到的技术细节。你有什么建议?

我不明白你为什么认为第一个更好。只需对您真正想要的进行子类化。 A Gtk.Box a Gtk.Widget 所以无论你在哪里可以使用后者,你都可以使用前者。

这取决于你头脑中的抽象。问问你自己:你的组件仅仅是一个自定义的 box 还是 more?

而且,你其实这里需要继承吗?也许你可以取消一个免费的工厂函数,它根据你的喜好创建一组 Gtk.Widgets。