使用QtRuby连接带参数的信号和槽函数。

6
我想知道如何连接带参数的信号(使用Ruby块)。
我知道如何连接不带参数的信号:
myCheckbox.connect(SIGNAL :clicked) { doStuff }

然而,这并不起作用:
myCheckbox.connect(SIGNAL :toggle) { doStuff }

这不起作用是因为toggle插槽需要一个参数void QAbstractButton::toggled(bool checked)。我如何在带有参数的情况下使其正常工作?

谢谢。


我以前没有尝试过QtRuby,但是可以试一下这个,看看是否有效: myCheckbox.connect(SIGNAL :toggle) { |checked| doStuff } - Kokizzu
1
是的,想到了那个,但不起作用 :( - Jean-Luc
尝试实现这个:http://pcapriotti.wordpress.com/2010/09/24/effective-qt-in-ruby-part-2/ - Kokizzu
2
我认为这有点荒谬了... 我刚刚决定执行 checkbox.connect( :SIGNAL "toggle(bool)" ) { |x| puts x } - Jean-Luc
1个回答

4

简而言之,您需要使用slots方法声明要连接的槽的方法签名:

class MainGUI < Qt::MainWindow
  # Declare all the custom slots that we will connect to
  # Can also use Symbol for slots with no params, e.g. :open and :save
  slots 'open()', 'save()',
        'tree_selected(const QModelIndex &,const QModelIndex &)'

  def initialize(parent=nil)
    super
    @ui = Ui_MainWin.new # Created by rbuic4 compiling a Qt Designer .ui file
    @ui.setupUi(self)    # Create the interface elements from Qt Designer
    connect_menus!
    populate_tree!
  end

  def connect_menus!
    # Fully explicit connection
    connect @ui.actionOpen, SIGNAL('triggered()'), self, SLOT('open()')

    # You can omit the third parameter if it is self
    connect @ui.actionSave, SIGNAL('triggered()'), SLOT('save()')

    # close() is provided by Qt::MainWindow, so we did not need to declare it
    connect @ui.actionQuit,   SIGNAL('triggered()'), SLOT('close()')       
  end

  # Add items to my QTreeView, notify me when the selection changes
  def populate_tree!
    tree = @ui.mytree
    tree.model = MyModel.new(self) # Inherits from Qt::AbstractItemModel
    connect(
      tree.selectionModel,
      SIGNAL('currentChanged(const QModelIndex &, const QModelIndex &)'),
      SLOT('tree_selected(const QModelIndex &,const QModelIndex &)')
    )
  end

  def tree_selected( current_index, previous_index )
    # …handle the selection change…
  end

  def open
    # …handle file open…
  end

  def save
    # …handle file save…
  end
end

请注意,传递给 SIGNALSLOT 的签名不包括任何变量名。
此外,正如您在评论中得出的结论,更简单(并且更符合 Ruby 风格)的做法是完全放弃“slot”概念,只需使用 Ruby 块将信号连接到调用所需的任何方法(或将逻辑内联)。使用以下语法,您无需使用 slots 方法预先声明方法或处理代码。
changed = SIGNAL('currentChanged(const QModelIndex &, const QModelIndex &)')

# Call my method directly
@ui.mytree.selectionMode.connect( changed, &method(:tree_selected) )

# Alternatively, just put the logic in the same spot as the connection
@ui.mytree.selectionMode.connect( changed ) do |current_index, previous_index|
  # …handle the change here…
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接