QT:将强类型枚举参数传递给slot

时间:2016-03-01 12:22:01

标签: c++ qt enums

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

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只能直接用于int和{{1}我无法弄清楚如何实现这一点。有没有相对简单的方法呢?

2 个答案:

答案 0 :(得分:3)

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

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

    sendRequest(request_type);

});
timer->start(10000);

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

答案 1 :(得分:2)

您可以创建connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout())); 广告位。像这样:

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

并在此插槽中:

{{1}}
相关问题