Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
[SOLVED]QTimer works incorrect..
my test code is:
PlayWidget::PlayWidget(QWidget *parent) :
_timer = new QTimer(this);
connect(_timer, SIGNAL(timeout()), this, SLOT(showInfo()));
static int counts = 0;
ui->label->setText(QString("count = %1").arg(++counts));
PlayWidget *pw = new PlayWidget();
The question is when there is only one PlayWidget it works fine,but when I create more(gt 1), they work abnormally.
I found that the counts increment equal to the PlayWidget I create.
Every PlayWidget and QTimer are new instance.
Why is this happening?
MuldeR last edited by
You made "counts" a static variable! Inside a function the keyword "static" before a variable means that this variable will retain its value between different function calls. It's essentially a global variable that is only visible/accessible inside the function. Most important, when you declare a "static" variable inside a class method, then all instances of that class will share the very same variable!
I am pretty sure that making "counts" a (non-static!) member variable of the PlayWidget class will fix it ;-)
Thanks, yes it's "static" make it wrong but I consider only static memeber variables share the variable,here the "counts " was a local variable.
I test the code in C and it works fine.
MuldeR last edited by
Nope! A variable declared "static" inside a function is not local anymore. As said before, it is essentially a global variable! Only difference to a global variable declared outside a function is that the "static" variable can only be accessed inside the function where it was declared. Otherwise it acts like a global variable. So if you declare a "static" variable inside some method of a class, as you did in your showInfo() method, then all instances of that class will share the very same variable - just like a static member variable (class variable). That is: With your code all instances of PlayWidget share the same "counts" value! That's basic C++ and not related to QTimer at all...
(Only exception to the above-mentioned is related to Template functions, but that's another issue I think ^^)
thanks,I know it now.