[英]QT: passing strongly typed enum argument to slot
I have defined a strongly typed enum like this: 我已经定义了一个强类型的枚举,如下所示:
enum class RequestType{
type1, type2, type3
};
Also I have a function defined as below: 我还有一个定义如下的函数:
sendRequest(RequestType request_type){
// actions here
}
I'd like to call the sendRequest
function every 10 seconds so in a simple case I would use something like this: 我想每10秒钟调用一次sendRequest
函数,因此在一个简单的情况下,我将使用如下所示的内容:
QTimer * timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(sendRequest()));
timer->start(10000);
Since I need to pass some arguments to sendRequest
function I guess I have to use QSignalMapper
but as QSignalMapper::setMapping
can be used straightforwardly only for int
and QString
, I cannot figure out how to implement this. 由于我需要将一些参数传递给sendRequest
函数,所以我想我必须使用QSignalMapper
但是由于QSignalMapper::setMapping
仅可以直接用于int
和QString
,所以我不知道如何实现此功能。 Is there any relatively simple way for it? 有没有相对简单的方法呢?
If you're using C++ 11 , you have the option of calling a lambda function in response to timeout
如果您使用的是C ++ 11 ,则可以选择调用lambda函数以响应timeout
QTimer * timer = new QTimer(this);
connect(timer, &QTimer::timeout, [=](){
sendRequest(request_type);
});
timer->start(10000);
Note that the connection method here (Qt 5) doesn't use the SIGNAL and SLOT macros, which is advantageous, as errors are caught at compilation, rather than during execution. 请注意,此处的连接方法(Qt 5)不使用SIGNAL和SLOT宏,这是有利的,因为错误是在编译时而不是在执行过程中捕获的。
You can create onTimeout
slot. 您可以创建onTimeout
插槽。 Something like this: 像这样:
connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
and in this slot: 并在此插槽中:
void onTimeout() {
RequestType request;
// fill request
sendRequest(request);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.