Tuesday, September 1, 2009

Yet another UI File loading

In past entries, I wrote 2 normal approaches of loading UI file in QtRuby.

Today I introduce a little unusual approach.

require 'Qt4'
require 'rexml/document'

# define method instead of qtuiloader
def Qt.load_ruby_from_ui(file_path, rbuic4_command = 'rbuic4')
doc = REXML::Document.new(::File.new(file_path))
top_widget_name = REXML::XPath.first(doc, '/ui/class/text()').value
parent_name = REXML::XPath.first(doc, '/ui/widget/@class')
eval `#{rbuic4_command} #{file_path}`
top_widget = const_get("Ui_#{top_widget_name.gsub(/\A(\w)/) {$1.upcase}}").new
parent = Qt::const_get(parent_name.value.gsub(/\AQ/, '')).new
top_widget.setupUi(parent)
parent
end

Qt::Application.new(ARGV) do
window = Qt.load_ruby_from_ui(
'/opt/qtsdk-2009.03/qt/examples/widgets/stylesheet/layouts/default.ui',
'/opt/ruby-1.9.1/bin/rbuic4')
window.show
exec
end

In this approach, evaluate the output of rbuic4 command, and then use Module#const_get to instantiate top widget class and its parent class.

No comments:

Post a Comment