qml向Qt的C++传数组参数

我们都知道qml和C++可以进行交互,但数据交互的过程中,一般只限于内置类型,比如int, bool,double等,如果是json或数组由C++传给qml,qml是可以解析的,但如果是qml传数组给C++呢,该如何传参及解析数组参数呢,C++中通过QVariantList来进处理参数处理,qml参数封装如下:

var infoArray = [];//先清空
infoArray.push("productVersion");
infoArray.push("productType");
infoArray.push("kernelType");
infoArray.push("currentCpuArchitecture");

C++解析:

QJsonObject SystemService::getSystemInfo(const QVariantList &list)
{
    for(int i = 0; i < list.count(); ++i)
    {
        QString typeName = list[i].toString();
  
    }

    return jsonObject;
}

完整的示例代码如下:

#ifndef SYSTEMSERVICE_H
#define SYSTEMSERVICE_H

#include <QObject>
#include <QSysInfo>
#include <QJsonObject>
#include <QVariantList>

class SystemService: public QObject
{
    Q_OBJECT

public:
    SystemService(QObject *parent = nullptr);

    Q_INVOKABLE QJsonObject getSystemInfo(const QVariantList &list);
    Q_INVOKABLE QString getSystemName();
};

#endif // SYSTEMSERVICE_H
#include "systemservice.h"


SystemService::SystemService(QObject *parent)
    :QObject(parent)
{

}

QJsonObject SystemService::getSystemInfo(const QVariantList &list)
{
    QString strProductVersion = QSysInfo::productVersion();
    QString strProductType = QSysInfo::productType();
    QString strKernelType = QSysInfo::kernelType();
    QString strCurrentCpuArchitecture = QSysInfo::currentCpuArchitecture();
    QJsonObject jsonObject;
    for(int i = 0; i < list.count(); ++i)
    {
        QString typeName = list[i].toString();
        if("productVersion" == typeName)
            jsonObject.insert("productVersion", strProductVersion);
        else if("productType" == typeName)
            jsonObject.insert("productType", strProductType);
        else if("kernelType" == typeName)
            jsonObject.insert("kernelType", strKernelType);
        else if("currentCpuArchitecture" == typeName)
            jsonObject.insert("currentCpuArchitecture", strCurrentCpuArchitecture);
    }

    return jsonObject;
}

QString SystemService::getSystemName()
{
    return QSysInfo::productType();
}
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "systemservice.h"

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

    QGuiApplication app(argc, argv);
    qmlRegisterType<SystemService>("CPPService", 1, 0, "SystemService");

    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);
    engine.load(url);

    return app.exec();
}
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import CPPService 1.0

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

    SystemService {
        id: systemService
    }

    Button {
        text: qsTr("获取信息")
        onClicked: {
            var infoArray = [];//先清空
            infoArray.push("productVersion");
            infoArray.push("productType");
            infoArray.push("kernelType");
            infoArray.push("currentCpuArchitecture");
            console.log("infoArray=======================" + infoArray)
            var systemInfo = systemService.getSystemInfo(infoArray)
            //arrayText.text = JSON.stringify(systemInfo)
            arrayText.text = systemInfo["productVersion"] + "\n" + systemInfo["productType"] + "\n" + systemInfo["kernelType"] + "\n" + systemInfo["currentCpuArchitecture"] + "\n"
            var type = systemService.getSystemName()
            typeText.text = type
            console.log("type=======================" + type)
        }
    }

    Text {
        id: arrayText
        color: "blue"
        anchors.top: parent.top
        anchors.topMargin: 100
        anchors.left: parent.left
        anchors.leftMargin: 20
        text: qsTr("text")
    }
    Text {
        id: typeText
        color: "red"
        anchors.top: parent.top
        anchors.topMargin: 100
        anchors.right: parent.right
        anchors.rightMargin: 20
        text: qsTr("type")
    }
}

运行结果:

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: QMLC++的交互可以通过Qt的信号槽机制来实现。在QML中声明一个信号,然后在C++中连接信号并且在槽函数中处理数组操作即可。 具体实现流程如下: 1. 在QML中声明一个信号signalToC,用于向C++发送数组。 ``` signal signalToC(variant array) ``` 2. 在C++中定义一个Q_INVOKABLE槽函数,用于接收QVariant类型的数组参数。 ``` Q_INVOKABLE void arraySlot(QVariant array) { QVariantList list = array.toList(); for (int i = 0; i < list.size(); ++i) { int element = list.at(i).toInt(); qDebug() << "element" << i << ":" << element; // 处理数组操作 } } ``` 3. 在C++中连接QML的信号与槽函数。 ``` QObject* rootObject = engine.rootObjects().at(0); QObject* qmlObject = rootObject->findChild<QObject*>("qmlObject"); QObject::connect(qmlObject, SIGNAL(signalToC(QVariant)), qmlObject, SLOT(arraySlot(QVariant))); ``` 4. 在QML中发送数组。 ``` signalToC([1, 2, 3]) ``` 通过以上步骤,就可以实现QMLC++之间的数组交互。在QML中可以将需要处理的数组作为参数发送给C++,然后C++再通过处理槽函数对数组进行处理。同时,在槽函数中也可以将处理结果发送回QML,进行下一步处理。 ### 回答2: QML是一种声明性的语言,通常用于跨平台开发。它可以用于构建用户界面,也可以用于实现业务逻辑,同时还支持各种数据类型的处理,包括数组。而C是一种结构化编程语言,通常适用于系统级编程。C语言中可以使用数组来存储和处理数据。 在QML中使用C语言的方式包括QML调用C函数和C直接访问QML对象。在QML中,使用JS Arrays来表示数组。我们可以在QML中声明一个整形数组,然后将其递给C代码。C代码可以通过参数列表或者函数调用方式获得数组。 当C处理完数据之后,可以将处理结果递回QML界面,以更新视图显示。因为QML和C之间的交互需要通过中间层来实现,所以性能方面需要进行一些考虑,以确保交互效率和数据处理效率。比如,可以使用异步回调机制获得更好的响应速度,同时也需要注意内存管理和资源释放。 总之,使用C与QML交互读取数组需要一定的开发经验和编程技巧。需要开发者熟悉QML和C编程语言,并且了解二者之间的差异和交互方式。只有具备了充足的知识和技能,才能够开发出高效、稳定、可靠的跨平台应用程序。 ### 回答3: 在QML中,可以使用JavaScript来实现对C++数组的交互读取。 首先,需要在C++代码中创建一个数组,并将其暴露给QML。可以使用Q_PROPERTY宏定义一个带有读取函数的成员变量,在QML中通过属性绑定来读取该数组。 例如,假设我们有一个名为Data的类,其中有一个整数数组: ``` class Data : public QObject { Q_OBJECT Q_PROPERTY(QVariantList array READ getArray NOTIFY arrayChanged) public: explicit Data(QObject *parent = nullptr); QVariantList getArray() const; Q_INVOKABLE void setArray(const QVariantList& array); signals: void arrayChanged(); private: int m_array[3]; }; ``` 在构造函数中将数组初始化,并将其转换为QVariantList类型,以便在QML中使用。注意,必须使用Q_INVOKABLE标记来声明可以从QML调用的成员函数。 ``` Data::Data(QObject *parent) : QObject(parent) { m_array[0] = 1; m_array[1] = 2; m_array[2] = 3; } QVariantList Data::getArray() const { QVariantList list; for (int i = 0; i < 3; i++) { list.append(m_array[i]); } return list; } void Data::setArray(const QVariantList& array) { for (int i = 0; i < 3; i++) { m_array[i] = array.value(i).toInt(); } emit arrayChanged(); } ``` 在QML中,可以使用该数组属性来读取和修改数组数据。例如,下面的QML代码使用一个ListView来显示数组: ``` import QtQuick 2.0 import MyApp 1.0 ListView { model: myData.array delegate: Text { text: modelData } } ``` 同时,也可以通过QML将新的数组数据写入到C++数组中: ``` import QtQuick 2.0 import MyApp 1.0 Button { text: "Update array" onClicked: { myData.setArray([4, 5, 6]) } } ``` 总之,使用Q_PROPERTY和Q_INVOKABLE可以实现在QML中读取和修改C++数组的功能,提供了很多灵活性和可扩展性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值