开发者

Qtimer not timing out QT, C++

I am learning C++ and using QT. I have a small program in which I am trying to update the text of the PushButton every second. The label being current time. I have a timer that should time out every second, but seems like it never does. 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(QTi开发者_开发百科me::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 will be greatly appreciated... The PushButton's text never changes...


You don't include the Q_OBJECT macro at the beginning of your class. You need it if your class declares any signals or slots (at least, if you want them to work). In fact, it's generally a good practice to include it in any class that is derived from QObject.

Modify your class declaration to look like this:

class HelloForm : public QDialog {
    Q_OBJECT;
public:
    // Actual code here.
};

http://doc.qt.io/qt-5/qobject.html#Q_OBJECT

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜