As an exercise in preparation for bigger things, I am trying to create a
custom widget that is a gtk.Entry with an added label.  I borrowed
liberally from examples, but I am not aware of any examples that do quite
what I am trying to do.  I can make this widget work by subclassing gtk.Bin
and adding the entry as a child, but what I really want is to have
a "self-contained" widget.  I think that I am close, but I have two
problems (that I know about) that have me completely stumped.  The first is
that I can't get the label to appear, although there appears to be space
for it.  The second is that the entry does not resize when I resize the
window.  Any suggestions would be greatly appreciated.  I'm hoping that
creating custom widgets gets easier after the first one.
-- 
Jeffrey Barish
import gtk
import pygtk
import gobject

class LabelEntry(gtk.Entry):
    __gtype_name__ = 'LabelEntry'
    __gproperties__ = {
        'label': (str, 'Entry Label', 'The label for the entry',
                  '', gobject.PARAM_READWRITE)
    }

    def __init__(self, label=None):
        gtk.Entry.__init__(self)
        gtk.widget_push_composite_child()
        self.label = gobject.new(gtk.Label, visible=True, xalign=0, yalign=0.5)
        gtk.widget_pop_composite_child()
        if label is not None:
            self.set_property('label', label)

    def do_size_request(self, requisition):
        label_req = gtk.gdk.Rectangle(0, 0, *self.label.size_request())
        requisition.width = label_req.width + 100 + 6
        requisition.height = 26

    def do_size_allocate(self, allocation):
        label_req = gtk.gdk.Rectangle(0, 0, *self.label.get_child_requisition())
        label_alloc = gtk.gdk.Rectangle()
        label_alloc.x = allocation.x
        label_alloc.y = allocation.y
        label_alloc.width = label_req.width
        label_alloc.height = allocation.height
        self.label.size_allocate(label_alloc)

        self_alloc = gtk.gdk.Rectangle()
        self_alloc.x = allocation.x + label_alloc.width + 6
        self_alloc.y = allocation.y
        self_alloc.width = allocation.width - label_alloc.width - 6
        self_alloc.height = allocation.height
        self.allocation = self_alloc

    def do_set_property(self, prop, value):
        if prop.name == 'label':
            self.label.set_text(value)

    def do_get_property(self, prop):
        if prop.name == 'label':
            return self.label.get_text()

if __name__ == '__main__':
    window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    window.set_size_request(350, 200)
    window.set_title("LabelEntry Test")
    window.connect('destroy', gtk.main_quit)

    le = LabelEntry('Entry:')
    window.add(le)
    window.show_all()
    gtk.main()


_______________________________________________
pygtk mailing list   [email protected]
http://www.daa.com.au/mailman/listinfo/pygtk
Read the PyGTK FAQ: http://www.async.com.br/faq/pygtk/

Reply via email to