我正在尝试从我的 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
谢谢你的帮助:)
最佳答案
当您执行 component.create();
时,您正在创建一个 Item
,其中有 Cloud
作为子项。如果你想获得 Cloud,你应该这样做:
QObject* myObject = component.create();
QQuickItem* item = qobject_cast<QQuickItem*>(myObject);
Cloud *cloud = item->findchild<Cloud*>();
已编辑:更新了 coyotte508 的评论。
关于c++ - QML/C++ 从 main.cpp 中的 QML 获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37431501/