简体   繁体   中英

How to pass an extra variable to a Qt slot

I would like to know how to pass a separate variable into a slot. I cant seem to get it to work. Is there some way around this?

This is my code:

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

If you don't want to declare MYVARIABLE in your class, but instead to have it tied to this particular signal/slot connection, you can connect the signal to a C++11 lambda using Qt5's new singal/slot syntax and then call your slot with that lambda.

For example you could write:

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

Another solution if you can't use C++11 and Qt5 is to use Qt's Property System to attach a variable to your QTimer* . This can be done with QObject::setProperty() .

Then in the slot you could use QObject::sender() to get your QTimer* and read the property back using QObject::property() .

However, note that it's not a very clean solution, and borderline abuse of the property system.

from 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.

you can try this

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


methodSlot()
{
    method(MYVARIABLE);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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