Important: Please read the Qt Code of Conduct -

Updating label content every 2 minutes

  • Hi!!!
    I'm a newbie in QT Creator. I would like to implement a very simple graphical interface based on a Label and a pushButtom.
    When pressing the button in the label the content of a txt file appears.
    The thing is that this same file will be changing every 2 minutes, so I would need that automatically and without pressing the button again, in the label this new content will appear, the change does not have to be done simultaneously.
    What function or functions should I turn to?
    Thanks in advance.

  • @nadales56
    You will use to set up a timer that repeatedly ticks every two minutes, and have its slot action update the text on the label. You will use to read the file's content. See how you go from there.

    If you later wish to be "clever", you might use to watch the file for changes to its content and only re-read at that point, rather than every two minutes regardless.

  • Thank you JonB!
    I have just make the text file content in the label!! =)

    I have some doubts about where or when should i use qtimer. I mean, first i clicked the button, so the information appear in the label, then i have to use qtimer to update the text automatically without clicking the buttom?

  • Lifetime Qt Champion

    yes, setting up timer will call your slot after the time you set.
    In that way, the timer can do what button does automatically.

  • So, in the mainwindow i have put something like:

    -> i call on_butttom_clicked
    -> i define the timer in 2 minuts

    } //kind of infinite while


  • Lifetime Qt Champion

    No, no infinite loop. That will kill the whole app.
    Use the QTimer. Then no loop is needed. Timer is the loop so to speak.

  • Lifetime Qt Champion

    Do like this

    class MainWindow : public QMainWindow
    QTimer *timer; // NEW
    void readFile(); // NEW to read the file and set to label
    private slots:
    void TimerSlot(); // NEW slot
        Ui::MainWindow *ui;
    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)
        timer = new QTimer(this); // create it
        connect(timer, &QTimer::timeout, this, &MainWindow::TimerSlot ); // connect it
    void MainWindow::readFile()
        // QFile readALL() etc and set to ui->label
    void MainWindow::on_pushButton_released()
    readFile(); // read file
    timer->start(120000); // 2 mins timer
    void MainWindow::TimerSlot()
        readFile(); // read file again

  • @mrjj
    Thank you so much for your help, i really appreciate it! =)
    It Works really well, as i want to be worked!

  • Lifetime Qt Champion

    Please dont forget to mark it as solved then :)

Log in to reply