【问题标题】:QtRuby connect signals and slots with parameters/argumentsQtRuby 使用参数/参数连接信号和插槽
【发布时间】:2012-12-04 00:59:18
【问题描述】:

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

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

myCheckbox.connect(SIGNAL :clicked) { doStuff }

但是,这不起作用:

myCheckbox.connect(SIGNAL :toggle) { doStuff }

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

谢谢。

【问题讨论】:

  • 以前从未尝试过 QtRuby,但不妨试试这个,看看是否可行: myCheckbox.connect(SIGNAL :toggle) { |checked|做事}
  • 是的,想到了,不起作用:(
  • 我觉得这有点荒谬......我刚决定做checkbox.connect( :SIGNAL "toggle(bool)" ) { |x| puts x }

标签: ruby qt qt4 qtruby


【解决方案1】:

对您的问题的简短回答是,您必须使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2012-10-15
    相关资源
    最近更新 更多