0

我正在根据这个导师http://qt-project.org/doc/qt-5.0/qtqml/qtqml-cppintegration-exposecppattributes.html在 Qt5 中将 C++ 类型的属性暴露给 QML 。当我运行它时,我的问题窗格中出现此错误错误:变量“QQmlComponent 组件”具有初始化程序但类型不完整不仅我有此错误我也有此错误未检测到我使用 Q_PROPERTY 创建的信号

C:\Users\Tekme\Documents\QtStuf\quick\QmlCpp\message.h:15: 错误:'authorChanged' 未在此范围内声明发出 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();
}
4

2 回答 2

5

你没有QQmlComponent在你的main.cpp

#include <QQmlComponent>

您还试图发出尚未声明的信号。你应该message.h像这样声明它:

signals:
    void authorChanged();

检查这个例子

于 2013-10-09T12:18:26.813 回答
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;
};
于 2013-10-09T12:27:48.067 回答