如何在Ruby Qt4中将自定义函数连接到QPushButton点击事件?
Hey there, let's sort out that button click connection issue for your QtRuby code! The problem with your current connect line is that you're trying to call do_sth() as a slot on the app object—but do_sth is your custom Ruby method, not a built-in Qt slot for the application.
QtRuby supports Ruby-style signal handling, so we don't need to force our method into a Qt slot. Here are two straightforward solutions:
Option 1: Use a Code Block (Simplest for Independent Methods)
You can directly pass a Ruby block to the connect method, which will run your do_sth function when the button is clicked:
Qt::Object.connect(btn, SIGNAL('clicked()')) { do_sth }
Option 2: Bind to a Method on an Object
If your custom method belongs to a class instance (a common pattern for larger apps), you can connect the signal directly to that object's method using the SLOT syntax—just make sure the method is part of the object you're targeting:
class CustomHandler def do_sth print "did something\n" end end handler = CustomHandler.new Qt::Object.connect(btn, SIGNAL('clicked()'), handler, SLOT('do_sth()'))
Full Corrected Code
Here's your complete fixed script with the first (simplest) approach, plus a small tweak to add a newline to the print statement so output is easier to read:
#!/usr/bin/env ruby require 'Qt4' def do_sth print "did something\n" 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)) # Corrected connection to run custom function Qt::Object.connect(btn, SIGNAL('clicked()')) { do_sth } btn.show() app.exec()
Now when you click the button, your do_sth function will run as expected!
内容的提问来源于stack exchange,提问作者mk92

