Nicholas Kinar
Nicholas Kinar

Reputation: 1470

Automatically updating QDateTimeEdit so that it displays the current system date and time

Using the Qt library, is there a way to automatically update a QDateTimeEdit using a signal such that the widget shows the current date and time in a similar fashion to a clock?

In the code sample below, dateTimeEditSystem is the QDateTimeEdit object. However, the setDateTime() function only operates once. I would like the QDateTimeEdit object to dynamically update. Is there a reliable way of doing this without using a timer (i.e. with signals and slots)? Or is a timer the only way of doing this?

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    // setup the UI
    ui->setupUi(this);
    // set the current date and time
    ui->dateTimeEditSystem->setDateTime( QDateTime::currentDateTime() );
}

I tried using a timer, but unfortunately the QDateTimeEdit did not update. Here is the complete mainwindow.cpp code. What am I doing wrong here?

#include <QTimer>

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->dateTimeEditSystem->setDateTime( QDateTime::currentDateTime() );

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT( updateTime() ));
    timer->start(1000);
}

void MainWindow::updateTime()
{
    ui->dateTimeEditSystem->setDateTime( QDateTime::currentDateTime() );
}

MainWindow::~MainWindow()
{
    delete ui;
}

UPDATE:

This is actually very easy to do. The reason why the code was not updating was due to the lack of a slot declaration in the mainwindow.h file. Here is the complete contents of the mainwindow.h header.

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;

 private slots:
     void updateTime();

};

#endif // MAINWINDOW_H

Upvotes: 1

Views: 6755

Answers (1)

RA.
RA.

Reputation: 7777

Automatically updating a QDateTimeEdit or any other clock widget within Qt is easily accomplished with a QTimer. Refer to the following examples for how to accomplish this:

http://qt-project.org/doc/qt-4.8/widgets-digitalclock.html

OR

http://qt-project.org/doc/qt-4.8/widgets-shapedclock.html

Note that the resolution of a QTimer varies on different operating systems, but for updates that need to occur ~1 second at a time, a QTimer should be fine on virtually all platforms. Refer to the following for more information on the resolution of QTimer:

http://qt-project.org/doc/qt-4.8/QTimer.html#accuracy-and-timer-resolution

Upvotes: 1

Related Questions