Mixing some GUI elements into your Ruby program

In Ruby, when you’ve got to grab some user input, a quick way of doing it is with a gets:


puts "What is your name?"
name = gets
puts "Hi #{name}"

But, we can make the interaction so much more pleasant through QtRuby:


require 'Qt'
Qt::Application.new(ARGV)
ok = Qt::Boolean.new

name = Qt::InputDialog::getText(”My Application”, “Enter your name”,
  Qt::LineEdit::Normal, nil, ok)

if(!ok.nil?)
  puts “Hi #{name}”
else
  raise “The user didn’t put in a name”
end

The above code makes a much nicer dialog box:

Or, consider it when having a user enter a password:


name = Qt::InputDialog::getText("My Application", "Enter your password",
  Qt::LineEdit::Password, nil, ok)

Qt::InputDialog is a convenience class for getting a quick user response - there are methods available for getting integers, floats, and items from a combo box. Of course, you can make much more sophisticated dialogs as well, but for getting a quick bit of input this class is very handy.

Comments are closed.