Skip to content

Instantly share code, notes, and snippets.

@yuntan
Created March 4, 2020 15:23
Show Gist options
  • Save yuntan/c9f7d83caff314c13ee2898ed51b9747 to your computer and use it in GitHub Desktop.
Save yuntan/c9f7d83caff314c13ee2898ed51b9747 to your computer and use it in GitHub Desktop.
require 'gtk3'
Gtk.init
class MyWidget < Gtk::Widget
type_register
def initialize
super
self.has_window = true
self.redraw_on_allocate = true
style_context.add_class 'mywidget'
end
def do_get_request_mode
puts "#{self.class.name}#do_get_request_mode"
Gtk::SizeRequestMode::HEIGHT_FOR_WIDTH
end
def do_get_preferred_width
puts "#{self.class.name}#do_get_preferred_width"
[100, 300]
end
def do_get_preferred_height
puts "#{self.class.name}#do_get_preferred_height"
get_preferred_height_for_width(preferred_width[0])
end
def do_get_preferred_height_for_width(width)
puts "#{self.class.name}#do_get_preferred_heigth_for_width(width=#{width})"
min = 100
h = width.zero? ? min : 9000 / width
[min, h]
end
def signal_do_size_allocate(allocation)
self.allocation = allocation
x, y, w, h = allocation.x, allocation.y, allocation.width, allocation.height
realized? and window.move_resize x, y, w, h
end
def signal_do_realize
x, y, w, h = allocation.x, allocation.y, allocation.width, allocation.height
attr = Gdk::WindowAttr.new w, h, :input_output, :child
attr.x = x
attr.y = y
attr.visual = visual
attr.event_mask = events | Gdk::EventMask::EXPOSURE_MASK
attr.wclass = :input_output
wat = Gdk::WindowAttributesType
mask = wat::X | wat::Y | wat::VISUAL
self.window = Gdk::Window.new parent_window, attr, mask
register_window window
self.realized = true
end
def signal_do_unrealize
unregister_window window
window.destroy
self.realized = false
end
def singla_do_map
super
window.show
end
def signal_do_unmap
super
window.hide
end
def signal_do_draw(cr)
x, y, w, h = allocation.x, allocation.y, allocation.width, allocation.height
Gtk.render_frame style_context, cr, x, y, w, h
Gtk.render_background style_context, cr, x, y, w, h
end
end
provider = Gtk::CssProvider.new
provider.load_from_data <<EOF
.mywidget { border: 1px solid red; }
EOF
screen = Gdk::Screen.default
Gtk::StyleContext.add_provider_for_screen screen, provider, :application
mywidget = MyWidget.new
p mywidget.request_mode
p mywidget.preferred_width
p mywidget.get_preferred_height_for_width(100)
box = Gtk::Box.new :vertical
box.add mywidget
box.show_all
window = Gtk::Window.new
window.add box
window.set_size_request 300, 300
window.present
Gtk.main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment