簡體   English   中英

從 QML 訪問屬性 c++ object

[英]Access an attribute c++ object from QML

我在理解如何使用來自 Z1A20607E15F3C3E77EECBD6830Z5 的 c++ singleton object 時遇到問題。 我知道我必須從 QObject class 繼承我的類,並且我必須公開這些屬性。 為了讓它們在 qml 中可用,我必須執行 setContextProperty("ClassName", &class name)。

However, if we admit that this class contains another object and that I want to be able to use it from the qml, I get errors like "cannot call method name" from undefined object.

例子:

APi.h

 class API : public QObject {
  Q_OBJECT
  Q_PROPERTY(User *user READ getUser WRITE setUser NOTIFY userChanged)
public:
  Q_INVOKABLE inline User *getUser() const {
    qDebug() << "get called";
    return user;
  };
  inline void setUser(User *new_user) { this->user = new_user; };

signals:
  void userChanged();

private:
  User *user;
};

用戶.h

#ifndef USER_H
#define USER_H

#include <QObject>
#include <QString>

class User: public QObject{
Q_OBJECT
public:
    Q_INVOKABLE inline QString &getName(){return name;}; // qrc:/main.qml:63: TypeError: Cannot call method 'getName' of undefined
private:
    QString name;
};
#endif // USER_H

主文件

#include <QQmlContext>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQuick3D/qquick3d.h>
#include "API.h"
#include "User.h"

int main(int argc, char *argv[]) {
  QGuiApplication app(argc, argv);
  QQmlApplicationEngine engine;
  API api;
  User user;
  api.setUser(&user);
  engine.rootContext()->setContextProperty("API", &api);

  qmlRegisterType<User>("User", 1, 0, "User");

  engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
  if (engine.rootObjects().isEmpty())
    return -1;

  return app.exec();
}

main.qml

import QtQuick
import QtQuick3D
import QtQuick.Controls
import QtQuick.Layouts

Window {

    Item{
        id: test
        Component.onCompleted: {
            console.log("Completed")
            API.getUser() // no error, getUser is called without error
            console.log(API.getUser().getName())
        }
    }
}

我有什么可能從 qml 到 API 訪問用戶 object?

您可以執行以下任何操作:

在 API class 中添加公共槽:

API.cpp:
QString API::getUserName()
{
    return user.getName();
}

main.qml:
Component.onCompleted: console.log( API.getUserName() )

在 API class 中將用戶設為 Q_PROPERTY:

API.h:
Q_PROPERTY( User* user READ user NOTIFY userChanged)

main.qml:
Component.onCompleted: console.log( API.user.getName() )

使用 QML 注冊用戶:

main.cpp:
qmlRegisterType<User>("MyUser", 1, 0, "MyUser");

main.qml:
Component.onCompleted: console.log( API.getUser().getName() )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM