Reputation: 35
I'm trying to get info from a new type -Cloud- instantiated in the example.qml from my main.cpp. I have no error of compilation neither of execution. I have only my empty object cloud.
Here my 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
Here my 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;
}
Here my 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();
}
And finally, here my example.qml
import QtQuick 2.0
import Sky 1.0
Item {
width: 300
height: 200
Item{
Cloud{
id:aCloud
name: "Cumulus"
}
}
}
I tried to solve my problem following those tutorials : Defining QML types Extending QML example
Thank you for your help :)
Upvotes: 1
Views: 213
Reputation: 1552
When you do component.create();
you are creating an Item
which has Cloud
as a child. If you want to get Cloud you should do something like:
QObject* myObject = component.create();
QQuickItem* item = qobject_cast<QQuickItem*>(myObject);
Cloud *cloud = item->findchild<Cloud*>();
EDITED: Updated with coyotte508 remarks.
Upvotes: 2
Reputation: 35
Thanks to Coyotte508 and perencia I succedded to find what was wrong :
in my main.cpp I had a QApplication
instead of a QGuiApplication
Upvotes: 0