QtRuby使用参数/参数连接信号和插槽

时间:2012-12-04 00:59:18

标签: ruby qt qt4 qtruby

我想知道如何连接到带参数的信号(使用Ruby块)。

我知道如何连接到不带参数的那个:

myCheckbox.connect(SIGNAL :clicked) { doStuff }

然而,这不起作用:

myCheckbox.connect(SIGNAL :toggle) { doStuff }

它不起作用,因为切换槽采用参数void QAbstractButton::toggled ( bool checked )。如何使用参数?

感谢。

1 个答案:

答案 0 :(得分: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的签名不包含任何变量名称。

另外,正如你在评论中总结的那样,去掉&#34;插槽&#34;更简单(更多Ruby-esque)。完全概念,只需使用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