如何将额外变量传递给 Qt 插槽

How to pass an extra variable to a Qt slot

我想知道如何将单独的变量传递到插槽中。 我似乎无法让它工作。有解决办法吗?

这是我的代码:

QTimer * timer = new QTimer();
connect(timer,SIGNAL(timeout()),this,SLOT(method(MYVARIABLE)));
timer->start(4000);

来自 http://doc.qt.io/qt-5/signalsandslots.html

The rule about whether to include arguments or not in the SIGNAL() and SLOT() macros, if the arguments have default values, is that the signature passed to the SIGNAL() macro must not have fewer arguments than the signature passed to the SLOT() macro.

你可以试试这个

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


methodSlot()
{
    method(MYVARIABLE);
}

如果您不想在 class 中声明 MYVARIABLE,而是将其绑定到这个特定的 signal/slot 连接,您可以将信号连接到 C ++11 lambda 使用 Qt5's new singal/slot syntax 然后用那个 lambda 调用你的插槽。

例如你可以这样写:

QTimer * timer = new QTimer();
connect(timer, &QTimer::timeout, [=]() {
     method(MYVARIABLE);
});
timer->start(4000);

如果不能使用 C++11 和 Qt5,另一种解决方案是使用 Qt's Property System to attach a variable to your QTimer*. This can be done with QObject::setProperty()

然后在插槽中您可以使用 QObject::sender() to get your QTimer* and read the property back using QObject::property()

但是,请注意,这不是一个非常干净的解决方案,并且属于对 属性 系统的滥用。