我试图从我的main.cpp中的example.qml中实例化一个新类型-Cloud来获取信息。 我没有编译错误也没有执行。我只有我的空物云。
这是我的cloud.h
#ifndef CLOUD_H
#define CLOUD_H
#include <QtQuick/QQuickPaintedItem>
#include <QColor>
class Cloud: public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(QColor color READ color WRITE setColor)
public:
Cloud(QObject *parent=0);
QString name() const;
void setName(const QString &name);
QColor color() const;
void setColor(const QColor &color);
private:
QString m_name;
QColor m_color;
};
#endif
这是我的cloud.cpp
#include "cloud.h"
#include <QPainter>
Cloud::Cloud(QObject *parent)
:QObject(parent)
{
}
QString Cloud::name() const{
return m_name;
}
void Cloud::setName(const QString &name)
{
m_name = name;
}
QColor Cloud::color() const
{
return m_color;
}
void Cloud::setColor(const QColor &color)
{
m_color = color;
}
这是我的main.cpp
#include "cloud.h"
#include <QtQuick/QQuickView>
#include <QApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterType<Cloud>("Sky", 1,0,"Cloud");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/example.qml")));
QQmlComponent component(&engine, QUrl((QStringLiteral("qrc:/example.qml"))));
Cloud *cloud = qobject_cast<Cloud*>(component.create());
if(cloud){
qWarning() << "The cloud is "<< cloud->name();
}else{
qWarning() << "there is no cloud" <<cloud;
}
return app.exec();
}
最后,这是我的example.qml
import QtQuick 2.0
import Sky 1.0
Item {
width: 300
height: 200
Item{
Cloud{
id:aCloud
name: "Cumulus"
}
}
}
我尝试按照这些教程解决我的问题: Defining QML types Extending QML example
感谢您的帮助:)
答案 0 :(得分:2)
当您执行component.create();
时,您正在创建一个Item
,其中有Cloud
。如果您想获得云,您应该执行以下操作:
QObject* myObject = component.create();
QQuickItem* item = qobject_cast<QQuickItem*>(myObject);
Cloud *cloud = item->findchild<Cloud*>();
已编辑:更新了coyotte508备注。
答案 1 :(得分:0)
感谢Coyotte508和perencia我成功找到了错误:
在我的main.cpp中,我有QApplication
而不是QGuiApplication