Thursday Night

Paul Betts’s personal website / blog / what-have-you

Qt4 Ruby and Metaprogramming 0.1 – Wiring up slots automatically

In my attempts to learn Qt 4 and QtRuby, it’s pretty obvious that there’s a huge potential for doing Rails-like things, such as declaration by convention. To this end, here’s an example of what you can do with the code I’m writing: this loads a UI file and wires something up to the Open action:

require ‘Qt’

class ActionOpenHandler < Qt::Object
    slots "on_activated()"

    def initialize(main = nil)
        super
        @main = main
    end

    def on_activated
        path = nil
        Qt::FileDialog.new do |fd|
            path = fd.get_open_file_name()
        end
        return unless path

        text = nil; File.open(path, ‘r’) {|f| text = f.read}
        @main.findChild(Qt::TextEdit, "textBrowser").text = text
    end
end

a = Qt::Application.new(ARGV)
QtSuperLoader.new.initialize_and_hook("./main.ui").show
a.exec

Next, I’m seeking to replace the ugly line "@main.findChild(Qt::TextEdit, "textBrowser").text = text" with the more palatable "@main.text_browser.text = text". However, this is a bit more tricky, because findChild creates strongly-typed objects – there may be some trickery to get around it though involving QMetaObject.

Here’s the files, including the code that supports it all: qttest.rb and Translator.ui

Written by Paul Betts

September 8th, 2007 at 10:20 pm

Posted in QT/KDE,Ruby