Qtimer没有超时QT,C++

rea*_*alz 2 c++ qt

我正在学习C++并使用QT.我有一个小程序,我试图每秒更新PushButton的文本.标签是当前时间.我有一个计时器应该每秒超时,但似乎它永远不会.这是代码.

头文件

#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 */
Run Code Online (Sandbox Code Playgroud)

CPP文件

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


}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激...... PushButton的文字永远不会改变......

Ste*_*e S 12

您不在Q_OBJECT课程开头包含宏.如果你的类声明任何信号或插​​槽(至少,如果你希望它们工作),你需要它.实际上,将它包含在从QObject派生的任何类中通常是一种很好的做法.

将您的类声明修改为如下所示:

class HelloForm : public QDialog {
    Q_OBJECT;
public:
    // Actual code here.
};
Run Code Online (Sandbox Code Playgroud)

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