【问题标题】:How to expose C++ struct to QML? [duplicate]如何将 C++ 结构暴露给 QML? [复制]
【发布时间】:2020-03-13 13:57:02
【问题描述】:

我的目标是在 ui 中显示角度和长度值。但是我什至无法从 qml 文件中访问该变量并将其转发到控制台。我已经实现了this topic,但没有希望。我需要帮助!

控制器.h

#ifndef CONTROLLER_H
#define CONTROLLER_H

#include <QObject>

struct MyStruct {
    float angle;
    uint16_t length;
};


class Controller : public QObject
{
    Q_OBJECT
public:

     explicit Controller(QObject *parent = nullptr);
     MyStruct plate;

};

#endif // CONTROLLER_H


main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <controller.h>
#include <QtQml>
#include <qquickview.h>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    Controller ctrl;
    QQmlContext *ctx=engine.rootContext();
    ctx->setContextProperty("controller", &ctrl);
    engine.load(url);

    return app.exec();
}


main.qml

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Button{
        onClicked: {
            console.log(controller.plate.length)
        }
    }


}


【问题讨论】:

  • 实际上我已经尝试过这个例子,但它也没有工作:(

标签: c++ qt qml


【解决方案1】:

由于您的 Controller 类继承自 QObject,因此应该可以从 QML 访问它。但是MyStruct 类型不会是原样,因为它不是从QObject 派生的。对于轻量级对象(不需要信号/槽),您可以改用Q_GADGET 宏,它将提供参与运行时系统所需的支持并支持反射。

struct MyStruct {
    Q_GADGET
    public:
        float angle;
        uint16_t length;
};

这将使您能够访问 QML 中的MyStruct 成员。虽然如果你想创建新的实例,你需要让它从Object 派生并使用qRegisterMetaType 注册它,如How to create new instance of a Q_GADGET struct in QML? 中所述

【讨论】:

  • 这基本上是我通过投票结束这个问题所链接到的......
  • @gavinb 添加 Q_GADGET 使我所有的结构变量都是私有的。任何建议。
  • @BerkantAy 只需在宏之后添加public: 行。我更新了答案。
  • 你是我的英雄@gavinb
  • 实际上我无法在我的 qml @gavinb 中访问 struct
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 2012-12-21
  • 2015-10-26
  • 1970-01-01
相关资源
最近更新 更多