2010-05-18 175 views
2

我正在學習C++並使用QT。 我有一個小程序,我試圖每秒更新一次PushButton的文本。標籤是當前時間。我有一個應該每秒超時的計時器,但似乎從未這樣做。這是代碼。Qtimer不會超時QT,C++

頭文件

#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文件

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


} 

任何幫助將不勝感激...按鈕的文字永遠不會改變......

+0

現在你已經感謝別人的答案...你應該接受它,使他們獲得聲譽(和你做的一樣好)。 – 2010-05-19 16:09:44

回答

12

你不」 t在課程開始時包含Q_OBJECT宏。如果你的班級宣佈任何信號或插​​槽(至少,如果你想讓它們工作),你需要它。事實上,將它包含在從QObject派生的任何類中通常都是一個好習慣。

修改類的聲明看起來像這樣:

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

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