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

QT: passing strongly typed enum argument to slot

本文关键字:参数传递 插槽 枚举 强类型 QT      更新时间:2023-10-16

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

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);
}