繁体   English   中英

QT:将强类型的枚举参数传递给插槽

[英]QT: passing strongly typed enum argument to slot

我已经定义了一个强类型的枚举,如下所示:

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 ,所以我不知道如何实现此功能。 有没有相对简单的方法呢?

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

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

    sendRequest(request_type);

});
timer->start(10000);

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

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

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

并在此插槽中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM