6

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

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

myCheckbox.connect(SIGNAL :clicked) { doStuff }

但是,这不起作用:

myCheckbox.connect(SIGNAL :toggle) { doStuff }

它不起作用,因为切换插槽带有一个参数void QAbstractButton::toggled ( bool checked )。我怎样才能使它与参数一起工作?

谢谢。

4

1 回答 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 块连接信号以调用您喜欢的任何方法(或将逻辑放在排队)。使用以下语法,您不需要使用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
于 2014-10-19T18:43:26.750 回答