【问题标题】:Work around for signal and slot argument limitation解决信号和槽参数限制
【发布时间】:2013-07-03 02:01:10
【问题描述】:

我想在点击按钮时制作一个按钮,它的文本变为“点击”。我试过了

connect(button1, SIGNAL(clicked()), this, SLOT(markClicked(button1))); 

其中this 指的是MainWindow

void MainWindow::markClicked(QPushButton *button) { button->setText("Clicked"); }

它似乎不起作用,因为我认为 SLOT 不能接受比 SIGNAL 更多的参数。是否有任何解决此限制的方法?

谢谢。

【问题讨论】:

    标签: qt qt4


    【解决方案1】:

    Qt 信号/槽机制只能将信号传递到具有类似参数的槽函数。作为一种解决方法,您应该使用QSignalMapper:

    QSignalMapper mapper;
    ...
    connect(button1, SIGNAL(clicked()), &mapper, SLOT(map()));
    mapper.setMapping(button1, button1); // not sure whether this is mandatory or not
    ...
    connect(&mapper, SIGNAL(mapped(QWidget*)), this, SLOT(markClicked(QWidget*)));
    

    而函数markClicked

    void MainWindow::markClicked(QWidget *widget) {
      QPushButton *button = qobject_cast<QPushButton*>(widget);
      button->setText("Clicked");
    }
    

    【讨论】:

      【解决方案2】:

      另一种方法是使用参数的默认值,然后使用 sender() 方法:

      在主窗口中:
      void markClicked(QPushButton *button = NULL);

      然后:
      connect(button1, SIGNAL(clicked()), this, SLOT(markClicked()));

      和:

      void MainWindow::markClicked(QPushButton *button) {
         if (button==NULL) { button = qobject_cast<QPushButton*>(sender()); }
          button->setText("Clicked");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-08
        • 2017-06-30
        • 1970-01-01
        • 1970-01-01
        • 2012-03-05
        • 1970-01-01
        • 2011-08-08
        • 1970-01-01
        相关资源
        最近更新 更多