2013-10-09 25 views
0

我正在根據此導師http://qt-project.org/doc/qt-5.0/qtqml/qtqml-cppintegration-exposecppattributes.html在Qt5中向CML公開C++類型的屬性。當我運行它我得到這個錯誤在我的問題窗格錯誤:變量'QQmlComponent組件'具有初始值設定項,但不完整的類型不僅我有這個錯誤我也有這個錯誤信號我創建使用Q_PROPERTY未檢測到錯誤:變量'QQmlComponent組件'具有初始值設定項,但在Qt5中不完整類型

C:\Users\Tekme\Documents\QtStuf\quick\QmlCpp\message.h:15: error: 'authorChanged' was not declared in this scope emit authorChanged(); ^

我的代碼是

#ifndef MESSAGE_H 
#define MESSAGE_H 
#include <QObject> 
class Message : public QObject 
{ 
Q_OBJECT 
Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged) 
public: 
    void setAuthor(const QString &a) { 
     if (a != m_author) { 
      m_author = a; 
      emit authorChanged(); 
     } 
    } 
    QString author() const { 
     return m_author; 
    } 
private: 
    QString m_author; 
}; 
#endif 

,並在我的main.cpp

#include "message.h" 
#include <QApplication> 
#include <QQmlEngine> 
#include <QQmlContext> 
int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 
    QQmlEngine engine; 
    Message msg; 
    engine.rootContext()->setContextProperty("msg",&msg); 
    QQmlComponent component(&engine, QUrl::fromLocalFile("main.qml")); 
    component.create(); 

    return a.exec(); 
} 

回答

3

您還沒有包括QQmlComponent頭在你的main.cpp

#include <QQmlComponent> 

您還試圖發出你還沒有宣佈的信號。你應該聲明它在你的message.h這樣的:

signals: 
    void authorChanged(); 

檢查this example

+0

thankssss。我所有的錯誤都消失了,非常感謝你。 qt文檔很棒,但對於像我這樣的初學者來說,這有點困難。 – realtekme

+1

@realtekme我確實認爲你正在關注的教程需要修復。它有一個缺少信號聲明的類的例子。 – thuga

+0

你是對的。特別是對於初學者而言,你會感到困惑。 – realtekme

2

我相信你需要添加:

signals: 
    void authorChanged(); 

到類像這樣:

class Message : public QObject 
{ 
Q_OBJECT 
Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged) 
public: 
    void setAuthor(const QString &a) { 
     if (a != m_author) { 
      m_author = a; 
      emit authorChanged(); 
     } 
    } 
    QString author() const { 
     return m_author; 
    } 
signals: 
    void authorChanged(); 
private: 
    QString m_author; 
}; 
+0

嗯。當我開始回答時,我發誓其他答案不在我的瀏覽器中。雖然我確實收到了一個通知,說我在完成一半後發佈了答案。 – drescherjm

相關問題