rubyqtqtruby

Acquiring a reference to the emitting widget with QtRuby


I'm currently connecting the signal to a function like this:

 dashboard.ui.start_button_r1.connect(:clicked, dashboard.ui.start_button_r1, :handler)

where start_button_r1 is a QPushButton

Now what I want is a reference to the sending widget within handler, since I will connect this signal to several widgets. Ideally I would like my handler function to receive a emitter argument I can play around with. I could put handlerwithin a class inheriting from Qt::Object (say HandlerContainer) and call sender(), but then how do I connect the signal to HandlerContainer's inner method? I tried instance.method(:handler), but connect doesn't receive slots in that way

I usually use this approach in PyQt, but can't figure out how to do it with Ruby. I feel like I'm doing something terribly wrong since there isn't much discussion on how to get the sender from within a slot using QtRuby. How is it usually done? I have read about QSignalMapper, but that seems awfully overkill for my use case.


Solution

  • You can do it with QObject::sender() function. As you've said inside handler slot, typecast sender() to the type, you expect, QPushButton in your case, and you,ve got a reference to sender object.

    In c++ it could be done like this:

    // inside handler method
    QPushButton *tmpBtn= dynamic_cast<QPushButton*>(sender());
    

    Edit:

     A minimal example on how to do this in Ruby:
    
    class SlotContainer < Qt::Object
       slots "handler()"
    
       def handler
        puts "called by: " + sender().to_s
       end
    end
    
    if $0 == __FILE__
        app = Qt::Application.new(ARGV) 
        ui = Ui_MainWindow.new
        container = SlotContainer.new
        window = Qt::MainWindow.new
        ui.setupUi(window)
        Qt::Object.connect(ui.pushButton, SIGNAL("clicked()"), container, SLOT("handler()"))
        window.show
        app.exec
    end