Important: Please read the Qt Code of Conduct -

[SOLVED]QTimer works incorrect..

  • my test code is:
    @#include "playwidget.h"
    #include "ui_playwidget.h"
    #include <QTimer>

    PlayWidget::PlayWidget(QWidget *parent) :
    ui(new Ui::PlayWidget)
    _timer = new QTimer(this);
    connect(_timer, SIGNAL(timeout()), this, SLOT(showInfo()));

    delete ui;

    void PlayWidget::showInfo()
    static int counts = 0;

    ui->label->setText(QString("count = %1").arg(++counts));


    @void MainWindow::on_pushButton_clicked()
    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?

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

  • @MuldeR MuldeR
    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.

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


Log in to reply