c++ - 如何加快对从 C++ 公开到 QML 的 QList<qreal> 的访问

标签 c++ qt reference qml qlist

我在访问 QList<qreal> 时遇到一些问题属性(property)。 我已经声明:

Q_PROPERTY(QList<qreal> circlePointsX READ circlePointsX NOTIFY circlePointsXChanged);
QList<qreal> circlePointsX(void) const
{
   return mCirclePointsX;
}

在 QML 文件中,我做了

pArea.circlesPointsX = paintAreaHelper.circlePointsX;

然后一些代码逐点读取:

    var cPointsX = circlesPointsX;
    var cPointsY = circlesPointsY;

    var noOfPoints = circlesPointsX.length - 4;
    for (var i = 0; i <= noOfPoints; i+=4)
    {
        ctx.moveTo(cPointsX[i], cPointsY[i]);
        ctx.lineTo(cPointsX[i+1], cPointsY[i+1]);
        ctx.lineTo(cPointsX[i+2], cPointsY[i+2]);
        ctx.lineTo(cPointsX[i+3], cPointsY[i+3]);
        ctx.lineTo(cPointsX[i], cPointsY[i]);
    }

当然属性的类型是var

property var circlesPointsX;@

和分配:

var cPointsX = circlesPointsX;

不会加快任何速度,因为它只是复制引用。

我对其进行了调试,对于每个循环访问,都会调用 c++ 方法。 我想从 c++ 复制数据一次,然后从“本地 qml 拷贝”访问它,而不是每次都调用 c++ getter。

最佳答案

documentation阐明了它:

If the sequence is exposed as a Q_PROPERTY, accessing any value in the sequence by index will cause the sequence data to be read from the QObject's property, then a read to occur. Similarly, modifying any value in the sequence will cause the sequence data to be read, and then the modification will be performed and the modified sequence will be written back to the QObject's property.

If the sequence is returned from a Q_INVOKABLE function, access and mutation is much cheaper, as no QObject property read or write occurs; instead, the C++ sequence data is accessed and modified directly.

因此,您的解决方案是将 circlePointsX 声明为:

Q_INVOKABLE QList<qreal> circlePointsX() const { return mCirclePointsX; }

您应该删除 circlePoints 属性,或将其重命名为其他名称。

吹毛求疵:将 void 放在参数列表中是一种 C 主义,在 C++ 中没有立足之地。在 C 中使用它的原因是 void foo() 等同于 void foo(...)。在 C++ 中不再是这种情况。

关于c++ - 如何加快对从 C++ 公开到 QML 的 QList<qreal> 的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19365563/

相关文章:

c++ - 具有类内初始化的默认默认构造函数的行为是什么?

c++ - 使用 Qt 测试本地连接

java - 何时创建变量(内存管理)

c++ - 为什么 "universal references"具有与右值引用相同的语法?

c++ - 图像未显示在 QGraphicsScene 中

.net - 在Microsoft的CLR中,用于异步方法调用的ref值类型参数存储在哪里?

c++ - 通过类函数添加到指针 vector

c++ - 无法使用 QProcess 启动 g++

c++ - 套接字 : multithreading doesn't work when client reads messages

c++ - 动态改变图标[QT/c++]