Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 457
hat_to_the_back Avatar asked Apr 16 '15 13:04

hat_to_the_back


2 Answers

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.

like image 53
tux3 Avatar answered Oct 27 '22 00:10

tux3


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);
}
like image 38
utarid Avatar answered Oct 27 '22 00:10

utarid