Re: how to set color on GtkButton?



Matthew Weier OPhinney said:
I've created a button that, when clicked, springs open a
GtkColorSelectionDialog. What I'd like to do is display the color on the
button, and update the color with the value returned by the dialog.

Gnome2::Color::Picker does this.
http://developer.gnome.org/doc/API/2.0/libgnomeui/gnomecolorpicker.html

it's implemented with a GdkPixbuf drawn to a GtkDrawingArea inside the button,
and they paint the color on the pixbuf.  something tells me that a GtkImage
would be easier, but they also have Atk bindings and color value drag and
drop, so i'd say use that if you can.


if you can't (e.g., you can't depend on Gnome2), then...

i hacked up a quick test app using Gtk and $widget->modify_bg, as you
mentioned.  it seems to work fine.  this one stores the color value in the
button, but draws the color as the background of an eventbox inside a frame
because i don't like the look of changing the color of the whole button.  you
could easily wrap this up in a class and to it properly, even installing an
object property that stores the color as a hexified string value.  (you'd need
Glib::Subclass to do the property trick; it's really easy.)

-=-=-=-=-=-=-
#!/usr/bin/perl -w

use Gtk2 -init;

$win = Gtk2::Window->new;
$win->signal_connect (delete_event => sub {Gtk2->main_quit;1});

$bn = Gtk2::Button->new;
$win->add ($bn);

$frame = Gtk2::Frame->new;
$bn->add ($frame);

$ebox = Gtk2::EventBox->new;
$ebox->set_size_request (15, 15);
$frame->add ($ebox);

$c = Gtk2::Gdk::Color->parse ('#ff0000');
$ebox->modify_bg ('normal', $c);
$ebox->modify_bg ('prelight', $c);
$ebox->modify_bg ('active', $c);
$bn->{colorspec} = Gtk2::ColorSelection->palette_to_string ($c);

$bn->signal_connect (clicked => sub {
        ($c) = Gtk2::ColorSelection->palette_from_string ($bn->{colorspec});
        $dlg = Gtk2::ColorSelectionDialog->new ('pick a color, any color');
        $dlg->colorsel->set_current_color ($c);
        if ('ok' eq $dlg->run) {
                $c = $dlg->colorsel->get_current_color;
                $ebox->modify_bg ('normal', $c);
                $ebox->modify_bg ('prelight', $c);
                $ebox->modify_bg ('active', $c);
                $bn->{colorspec} = Gtk2::ColorSelection->palette_to_string ($c);
        }
        $dlg->destroy;
});

$win->show_all;
Gtk2->main;
-=-=-=-=-

-- 
muppet <scott at asofyet dot org>



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