Re: subclass, custom widget



Jim Donoghue said:
How do I properly create a custom widget? What I need to do is create a
HBox with a label, an entry, and a button, that I can use like this:

use Things;

my $vbox = Gtk2::VBox->new(0,6);

my $thing = SomeThing->new();

$vbox->add($thing);

....

Where SomeThing is the custom widget.

How do I get SomeThing to inherit the properties necessary to treat it
as a container?

depending on what you're doing you probably don't need to use Glib::Subclass.
take a look at http://gtk2-perl.sourceforge.net/faq/#16

it should look something like: (note this isn't compiled/tested code, but it
should be close)

package Gtk2::Something;

use strict;
use warnings;
use Carp;
use Gtk2;
# this is the all important line
use base 'Gtk2::VBox';

sub new
{
        my $class = shift;

        # first to parmas to this function are the params for the vbox new call
        my $self = Gtk2::Vbox->new(shift, shift);

        # rebless it to an Gtk2::Something
        bless $self, $class;

        # use the third param as the label text
        $self->{label} = Gtk2::Label->new(shift)
        $self->{entry} = Gtk2::Entry->new;
        # the fourth param will be put into the entry to start
        $self->{entry}->set_text(shift);
        # the fifth param will be the button label
        $self->{button} = Gtk2::Button->new(shift);

        # obviously pack them how you want
        $self->pack_start($self->{label}, 0, 0, 0);
        $self->pack_start($self->{entry}, 0, 0, 0);
        $self->pack_start($self->{button}, 0, 0, 0);

        return $self;
}

sub show
{
        my $self = shift;
        $self->{label}->show;
        $self->{entry}->show;
        $self->{button}->show;
        $self->SUPER::show;
}

# there's probably a few more methods that you might want to override

then you would use it like:

my $vbox = Gtk2::VBox->new(0,6);
# you obviously need to change the way params work to suit your actual needs.
my $thing = Gtk2::SomeThing->new(0, 6, 'label txt', 'entry txt', 'button txt');
$vbox->pack_start($thing, 0, 0, 0);
$thing->{entry}->set_text('foo');

-rm



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]