简体   繁体   中英

QML/C++ getting info from QML in main.cpp

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 :)

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.

感谢Coyotte508和perencia,我成功地找到了问题所在:在main.cpp中,我有一个QApplication而不是QGuiApplication

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM