首页 > 解决方案 > 有没有办法有效地更新 QML 中的 CAN 数据?

问题描述

目前我正在使用文件中的 socketcan API 实时接收 CAN 数据main.cpp

我不断更新 CAN 的数据帧中的一个变量main.cpp

main.cpp我想通过将包含 CAN 数据帧的变量传递给 QML 动画仪表来实时表达仪表。

我需要实时检测QML中包含CAN数据的变量的变化。想问问有没有有效的方法。

我尝试使用emit. 但是,emit里面写的函数device-> connect (device, & QCanBusDevice :: framesReceived, [device] () {...}不起作用。

使用它时,我收到错误

' this' 不能在此上下文中隐式捕获。

我查找了错误,但没有找到答案。

if (QCanBus::instance()->plugins().contains(QStringLiteral("socketcan"))) {
            qWarning() << "plugin available";
        }

        QString errorString;
        QCanBusDevice *device = QCanBus::instance()->createDevice(
            QStringLiteral("socketcan"), QStringLiteral("vcan0"), &errorString);
        if (!device) {
            qWarning() << errorString;
        } else {
            device->connectDevice();
            std::cout << "connected vcan0" << std::endl;

            device->connect(device, &QCanBusDevice::framesReceived, [device]() {

            QCanBusFrame frame = device->readFrame();
            QString testV = frame.toString();

            QString qvSpeed = frame.payload();

            std::string text = testV.toUtf8().constData();
            std::string vSpeed = qvSpeed.toUtf8().constData();

            //At that point the vVal values ​​are being updated in real time.
            //I want to pass the updated vVal to qml gui in real time.
            int vVal = static_cast<int>(frame.payload()[0]);
            //emit sendMessage(vVal); // 'this' cannot be implicitly captured in this context error.

            std::cout << text << std::endl;
            });
        }

截至目前,main.cpp无法发送数据,QML 也无法解决该错误。

里面device-> connectemit sendMessage (vVal);会导致“'this' cannot be implicitly capture in this context”的错误。

我想知道是否有一种通过实时表达QML GUI数据来实现动画的好方法。

标签: c++qtqml

解决方案


您的捕获子句仅捕获device. 您还需要显式捕获this

device->connect(device, &QCanBusDevice::framesReceived, [this,device]{ /*...*/ });

顺便说一句,请注意,无需()为无参数 lambda 表达式指定 。


推荐阅读