首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有参数/自变量的QtRuby连接信号和插槽

带有参数/自变量的QtRuby连接信号和插槽
EN

Stack Overflow用户
提问于 2012-12-04 08:59:18
回答 1查看 1.1K关注 0票数 6

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

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

代码语言:javascript
复制
myCheckbox.connect(SIGNAL :clicked) { doStuff }

但是,这不起作用:

代码语言:javascript
复制
myCheckbox.connect(SIGNAL :toggle) { doStuff }

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

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-20 02:43:27

对您的问题的简短回答是,您必须使用slots方法声明要连接到的插槽的方法签名:

代码语言:javascript
复制
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风格)的做法是完全摆脱“槽”的概念,只使用Ruby块来连接信号以调用您喜欢的任何方法(或者将逻辑内联)。使用以下语法,您不需要使用 slots方法来预先声明您的方法或处理代码。

代码语言:javascript
复制
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
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13694478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档