gpt4 book ai didi

arrays - 如何将二维 float 组从 QML 传递到 C++?

转载 作者:行者123 更新时间:2023-12-01 21:09:17 32 4
gpt4 key购买 nike

我在 QML 中有一个二维 float 组。我如何在 C++ 中获取它的值。

我在 C++ 中创建了一个类,并完成了 qmlRegisterType 的部分。该类现在可以在 QML 中访问。

请举例说明。


这是我尝试过的:

标题:

#include <QQuickItem>
#include <iostream>

class Controller : public QObject
{
Q_OBJECT

Q_PROPERTY(QList <QVariantList> names READ names WRITE setnames NOTIFY namesChanged)
QList <QVariantList> m_names;

public:
Controller()
{
}
~Controller() {
}

QList <QVariantList> names() const
{
return m_names;
}

public slots:
void setnames(QList <QVariantList> arg)
{
QVariantList p;
if (arg.size () > 0)
{
p = arg.first ();
std::cout << "\narg: \n" << p[0].toInt ();
}
else
std::cout << "\nqqqq " << arg.size () << "\n";
}

signals:
void namesChanged(QList <QVariantList> arg);
};

qml

import QtQuick 2.0
import FromCpp 1.0

Rectangle
{
property variant arras: [[1,2,3], [4,5,6]]
Controller
{
id: ppp
}

MouseArea
{
anchors.fill: parent
onClicked:
{
ppp.setnames(arras)
console.log(arras.length)
}
}
}

QtCreator 的确切输出:

Starting /home/***/documents/test/build-junk-Desktop_Qt_5_1_0_GCC_64bit-Debug/junk...
QML debugging is enabled. Only use this in a safe environment.
2

qqqq 0
QThreadStorage: Thread 0x181e270 exited after QThreadStorage 2 destroyed
/home/***/documents/test/build-junk-Desktop_Qt_5_1_0_GCC_64bit-Debug/junk exited with code 0

///

在这里,正如您所见,QML 中二维数组的大小正确打印为 2,而 C++ 中打印的大小为 0。

为什么会这样?请解释。

最佳答案

根据 user1095108's answer ,为了访问传递给 C++ 的 QML 2 Dim 数组的内部元素,我们需要将每一行转换为列表,如下所示:

QML部分:

import QtQuick 2.0
import FromCpp 1.0

Rectangle
{
property variant twoDimArray: [[1,2,3], [4,5,6]]
Controller
{
id: controllerA
}

MouseArea
{
anchors.fill: parent
onClicked:
{
controllerA.setname (twoDimArray)
}
}
}

C++部分:

void setname (QVariantList arg)  
{
if (arg.size())
{
QList <QVariant> p = arg[0].toList();

std::cout << "\nRow0 0:" << p[0].toInt ();
std::cout << "\nRow0 1:" << p[1].toInt ();
std::cout << "\nRow0 2:" << p[2].toInt ();

std::cout << "\n";

QList <QVariant> p1 = arg[1].toList();

std::cout << "\nRow1 0:" << p1[0].toInt ();
std::cout << "\nRow1 1:" << p1[1].toInt ();
std::cout << "\nRow1 2:" << p1[2].toInt ();
}
}

输出:

Starting /home/.../documents/test/build-junk-Desktop_Qt_5_1_0_GCC_64bit-Debug/junk...
QML debugging is enabled. Only use this in a safe environment.

Row0 0:1
Row0 1:2
Row0 2:3

Row1 0:4
Row1 1:5
Row1 2:6/home/.../documents/test/build-junk-Desktop_Qt_5_1_0_GCC_64bit-Debug/junk exited with code 0

关于arrays - 如何将二维 float 组从 QML 传递到 C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26056776/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com