首页 > 解决方案 > QML如何访问Cpp头定义

问题描述

我已经有一个带有定义定义的头文件。

下面是define.h的一些例子

定义.h

#define STR_STEP0       "step0"
#define STR_STEP1       "step1"
#define STR_STEP2       "step2"
#define STR_STEP3       "step3"
#define STR_STEP4       "step4"
#define STR_STEP5       "step5"
#define STR_STEP6       "step6"
#define STR_STEP7       "step7"
#define STR_STEP8       "step8"

我想按原样使用 QML 中 define.h 文件的定义值。

我已经知道 Q_INVOKABLE() 和 Q_PROPERTY()。使用这两种方法,#define 变量无法直接从 qml 中读取。

请告诉我如何在 qml 中访问 define.h 中的变量。

标签: qtqml

解决方案


您可以通过创建 C++ 类发送。当您在 C++ 上发出这些定义的值时,您可以在 QML 端阅读。这是一个例子,你可以试试:

主文件

#include <QApplication>
#include <QQmlApplicationEngine>
#include "sender.h"
#include <QQmlContext>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    qmlRegisterType<Sender>("Sender", 1, 0, "Sender");
    Sender sender;
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("Sender", &sender);
    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);
    engine.load(url);

    return app.exec();
}

发件人.h

#ifndef SENDER_H
#define SENDER_H

#include <QObject>

class Sender: public QObject
{
    Q_OBJECT
public:
    explicit Sender(QObject *parent = nullptr);

public slots:

    void send_defined();
signals:
    void sendDefined(QString str);
};

#endif // SENDER_H

发件人.cpp

#include "sender.h"

#define STR_STEP0       "step0"
#define STR_STEP1       "step1"
#define STR_STEP2       "step2"
#define STR_STEP3       "step3"
#define STR_STEP4       "step4"
#define STR_STEP5       "step5"
#define STR_STEP6       "step6"
#define STR_STEP7       "step7"
#define STR_STEP8       "step8"

Sender::Sender(QObject *parent)
{
}

void Sender::send_defined()
{
    emit sendDefined(STR_STEP0);
    emit sendDefined(STR_STEP1);
    emit sendDefined(STR_STEP2);
    emit sendDefined(STR_STEP3);
    emit sendDefined(STR_STEP4);
    emit sendDefined(STR_STEP5);
    emit sendDefined(STR_STEP6);
    emit sendDefined(STR_STEP7);
    emit sendDefined(STR_STEP8);
}

main.qml

import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.0

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

    Connections{
        target: Sender

        onSendDefined:{
            console.log(str)
        }

    }
    Button{
        text: "Test"
        onClicked: {
            Sender.send_defined()
        }
    }

}

推荐阅读