0

I want to execute a user defined function after a button was pressed. I don't know how to use the connect function correctly to achieve the behavior specified in the code snippet.

#!/usr/bin/env ruby
require 'Qt4'

def do_sth
  print "did something"
end

app = Qt::Application.new(ARGV)

btn = Qt::PushButton.new('Button')
btn.resize(75, 30)
btn.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold))

# A button click will close the application.
#Qt::Object.connect(btn, SIGNAL('clicked()'),app, SLOT('quit()'))
#
# FIXME How to execute the function do_sth if the button was pressed?
Qt::Object.connect(btn, SIGNAL('clicked()'),app, SLOT('do_sth()'))

btn.show()
app.exec()
mk92
  • 81
  • 1
  • 5
  • 1
    I am not familiar with Qt ruby bindings, so this is a comment rather than an answer. Generally you should have `do_sth()` defined as a slot in a `QObject` subclass, create a new instance of that subclass (`my_qobject`), then `Qt::Object.connect(btn, SIGNAL('clicked()'),my_qobject, SLOT('do_sth()'))`. Another option that come into mind is to use ruby [Monkey patching capabilities](https://stackoverflow.com/q/394144/2666212) to add your `do_sth()` method to the `Qt::Application` class at runtime (but I think that this is not generally regarded as good practice) – Mike May 11 '18 at 09:51

1 Answers1

0

Thanks for your hint, it worked the way you suggested.

#!/usr/bin/env ruby
require 'Qt4'

class Qo < Qt::Object
  slots 'do_sth()'
  slots 'bla()'

  def do_sth
    puts "did something"
  end

  def bla
    puts "blabla"
  end
end

qobj = Qo.new
app = Qt::Application.new(ARGV)

btn = Qt::PushButton.new('Button')
btn.resize(75, 30)
btn.setFont(Qt::Font.new('Times', 18, Qt::Font::Bold))

Qt::Object.connect(btn, SIGNAL('clicked()'),qobj, SLOT('do_sth()'))
Qt::Object.connect(btn, SIGNAL('pressed()'),qobj, SLOT('bla()'))

btn.show()
app.exec()
mk92
  • 81
  • 1
  • 5
  • 1
    You probably want to inherit the whole window from `Qt::Widget`. There's a good tutorial here on layout and widget management: http://zetcode.com/gui/rubyqt/ – Casper May 11 '18 at 11:00