Qtimer does not sync QT, C ++
I am learning C ++ and using QT. I have a little program where I am trying to update the text of a PushButton every second. The label is the current time. I have a timer that needs to time out every second, but it never seems to do that. here's the code.
Header file
#ifndef _HELLOFORM_H
#define _HELLOFORM_H
#include "ui_HelloForm.h"
class HelloForm : public QDialog {
public:
HelloForm();
virtual ~HelloForm();
public slots:
void textChanged(const QString& text);
void updateCaption();
private:
Ui::HelloForm widget;
};
#endif /* _HELLOFORM_H */
CPP file
#include "HelloForm.h"
#include <QTimer>
#include <QtGui/QPushButton>
#include <QTime>
HelloForm::HelloForm(){
widget.setupUi(this);
widget.pushButton->setText(QTime::currentTime().toString());
widget.pushButton->setFont(QFont( "Times", 9, QFont::Bold ) );
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateCaption()));
timer->start(1000);
connect(widget.pushButton, SIGNAL(clicked()), qApp, SLOT(quit()) );
connect(widget.nameEdit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&)));
}
HelloForm::~HelloForm() {
}
void HelloForm::textChanged(const QString& text) {
if (0 < text.trimmed().length()) {
widget.helloEdit->setText("Hello " + text.trimmed() + "!");
} else {
widget.helloEdit->clear();
}
}
void HelloForm::updateCaption() {
QString myVar;
myVar = QTime::currentTime().toString();
widget.pushButton->setText(myVar);
}
Any help would be greatly appreciated ... The PushButton text never changes ...
+2
a source to share
1 answer
You don't include a macro Q_OBJECT
at the beginning of your class. This is necessary if your class declares any signals or slots (at least if you want them to work). In fact, it is generally good practice to include it in any class derived from a QObject.
Modify the class declaration as follows:
class HelloForm : public QDialog {
Q_OBJECT;
public:
// Actual code here.
};
+12
a source to share