qt - 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 中的变量。
解决方案
您可以通过创建 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()
}
}
}
推荐阅读
- javascript - 如何禁用页面加载?
- serverless-framework - 在无服务器框架中找不到满足声明的有效选项
- nativescript - saveToFile 未将图像显示到图库中
- c# - ASP.NET Core 防止 api 路由的 spa-fallback 路由
- reactjs - 如何使用来自另一个组件的变量(保存为字符串的 URL)?
- php - wp_destroy_current_session() 是否也会以正确的方式处理 woocommerce 会话?
- html - 使用CSS在类中将内容居中对齐?
- javascript - 在同一页面上动态显示不同地区的多种货币价格
- php - Laravel Telescope 没有在配置文件夹中添加望远镜.php
- python-3.x - MacOS 上 python-crfsuite 的安装错误