Identifying dynamically created Widgets in action binding (Ruby)

Hello,

I am trying to create multiple widgets dynamically in Ruby, but haven't yet figured out a way to identify the widget later which sent the action signal from within the action function. Here is an example code:

def test(buttonName)
puts("Clicked: " + buttonName)
end

dialog = RBA::QDialog::new
vlayout = RBA::QVBoxLayout::new(dialog)

names = Array.new
names.append("button1")
names.append("button2")
names.append("button3")

for i in 0..names.length-1
b = RBA::QPushButton.new(names[i], dialog)
b.objectName = names[i]

b.clicked do
puts(self.to_s)
puts(b.objectName)
end

vlayout.addWidget(b)
end

dialog.show()

I have not found a way to identify the calling widget within the action function, since the self keyword seems to be handled differently in ruby than in python. If there is a way to accomplish this, some feedback would be greatly appreciated.

Comments

  • Hi!

    You could use QDialogButtonBox and handle its clicked signal for for same purpose.

  • edited April 2023

    @Sneha_123 your code becomes more readable if you add code block Markdown markup (a single line with triple backticks before and after the code - same as on github for example).

    One way to achieve the desired behavior is by putting an annotated receiver object between the signal and your handler:

    dialog = RBA::QDialog::new
    vlayout = RBA::QVBoxLayout::new(dialog)
    
    names = [ "button1", "button2", "button3" ]
    
    class ProcWithSender < Proc
      def initialize(sender, &block)
        @sender = sender
        @block = block
      end
      def call(*args)
        @block.call(@sender, *args)
      end
    end
    
    for i in 0..names.length-1
    
      b = RBA::QPushButton.new(names[i], dialog)
      b.objectName = names[i]
    
      b.clicked = ProcWithSender::new(b) do |sender,*args|
        puts("clicked #{sender.objectName}")
      end
    
      vlayout.addWidget(b)
    
    end
    
    dialog.exec()
    

    Matthias

Sign In or Register to comment.