【问题标题】:QT: passing strongly typed enum argument to slotQT:将强类型枚举参数传递给插槽
【发布时间】:2016-03-01 12:22:01
【问题描述】:

我已经定义了一个像这样的强类型枚举:

enum class RequestType{ 
    type1, type2, type3 
};

我还有一个函数定义如下:

sendRequest(RequestType request_type){ 
    // actions here 
}

我想每 10 秒调用一次 sendRequest 函数,所以在一个简单的情况下,我会使用如下代码:

QTimer * timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(sendRequest()));
timer->start(10000);

由于我需要将一些参数传递给sendRequest 函数,我想我必须使用QSignalMapper,但因为QSignalMapper::setMapping 只能直接用于intQString,所以我不知道如何实现这。有没有比较简单的方法呢?

【问题讨论】:

  • 请记住,强类型枚举需要注册为元类型。
  • @user3528438 你能举个例子吗

标签: c++ qt enums


【解决方案1】:

如果您是 using C++ 11,您可以选择调用 lambda 函数来响应 timeout

QTimer * timer = new QTimer(this);
connect(timer, &QTimer::timeout, [=](){

    sendRequest(request_type);

});
timer->start(10000);

请注意,这里的连接方法 (Qt 5) 不使用 SIGNAL 和 SLOT 宏,这是有利的,因为错误是在编译时捕获的,而不是在执行期间。

【讨论】:

    【解决方案2】:

    您可以创建onTimeout 插槽。像这样的:

    connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
    

    在这个位置:

    void onTimeout() {
      RequestType request;
      // fill request
      sendRequest(request);
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 2011-05-08
      • 2013-11-11
      • 2011-07-06
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多