Skip to content

Instantly share code, notes, and snippets.

@diazvictor
Created February 16, 2021 16:09
Show Gist options
  • Save diazvictor/f0e5e332c69c2549853a7577f2241f69 to your computer and use it in GitHub Desktop.
Save diazvictor/f0e5e332c69c2549853a7577f2241f69 to your computer and use it in GitHub Desktop.
How To Set Placeholder Text in Gtk.TextView With LGI (Lua + Gtk)
local lgi = require('lgi')
local Gtk = lgi.require('Gtk', '3.0')
--- Some widgets were added to keep the initial focus on others.
local window = Gtk.Window {
title = 'TextView With Placeholder',
width = 400,
height = 400,
window_position = Gtk.WindowPosition.CENTER,
{
Gtk.Box {
id = 'box',
visible = true,
can_focus = false,
orientation = Gtk.Orientation.VERTICAL,
{
Gtk.Button {
visible = true,
can_focus = true,
label = 'button'
},
expand = false,
fill = true,
position = 0
},
{
Gtk.Entry {
visible = true,
can_focus = true,
placeholder_text = 'This is an entry and below is a textview'
},
expand = false,
fill = true,
position = 1
},
{
Gtk.ScrolledWindow {
id = 'scroll',
visible = true
},
expand = true,
fill = true,
position = 2
}
}
},
on_destroy = function()
Gtk.main_quit()
end
}
local buffer_text = Gtk.TextBuffer {
text = 'This is the placeholder text...'
}
local textview = Gtk.TextView {
visible = true,
can_focus = true,
vexpand = true,
wrap_mode = Gtk.WrapMode.WORDCHAR,
buffer = buffer_text,
accepts_tab = false
}
--- When the TextView has the focus
function textview:on_focus_in_event (self, event)
if (buffer_text:get_text(buffer_text:get_start_iter(), buffer_text:get_end_iter(), true) == placeholder_str) then
buffer_text.text = ''
end
end
placeholder_str = 'This is the placeholder text...'
--- When the TextView has the focus I delete its current content (the placeholder).
function textview:on_focus_out_event (self, event)
if (buffer_text:get_text(buffer_text:get_start_iter(), buffer_text:get_end_iter(), true) == '') then
buffer_text.text = placeholder_str
end
end
window.child.scroll:add(textview)
window:show_all()
Gtk.main()
--[[
References:
* https://valadoc.org/gtk+-3.0/Gtk.TextView.html
* https://valadoc.org/gtk+-3.0/Gtk.TextBuffer.html
* https://stackoverflow.com/questions/45422460/how-to-set-placeholder-text-in-gtk-textview
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment