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

标签 ruby qt qt4 qtruby

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

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

myCheckbox.connect(SIGNAL :clicked) { doStuff }

但是,这不起作用:

myCheckbox.connect(SIGNAL :toggle) { doStuff }

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

谢谢。

最佳答案

对您的问题的简短回答是,您必须使用 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 block 连接信号以调用您喜欢的任何方法(或将逻辑内联)。使用以下语法,您不需要需要使用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

关于ruby - QtRuby 使用参数/参数连接信号和槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13694478/

相关文章:

c++ - 当用户使用 QTableWidget 中的键盘(Key_Up 和 Key_Down)更改行时发出信号

c++ - 使用 Qt4 的简单菜单栏

ruby-on-rails - 服务器是否在主机 "localhost"(::1) 上运行并在端口 5432 上接受 TCP/IP 连接?

ruby - 如何从数据库生成事件记录模型

c++ - Qt按钮没有出现在主窗口中

c++ - QSerialPort 的 readAll() 不包括最后发送的响应

python - 带有测试语句的 while 循环的惯用 Python 版本的 Ruby 代码?

ruby-on-rails - 在 ruby​​ 中批量创建具有嵌套属性的对象

python - Ubuntu 中没有出现 PyQt4 菜单栏

qt - QGridLayout中的QWidget边框问题