qml: ReferenceError: serial is not defined

qml编译警告:qrc:/Form02.qml:67: ReferenceError: serial is not defined

serial是我自定义的一个串口线程,在编译时报警告说serial未定义,但又能正常访问获取数据,使用代码示例如下:

示例代码:

cpp 复制代码
{
    //1
    ui->quickWidget_2->setSource(QUrl("qrc:/Form02.qml"));
    //2
    serial = new SerialPort;
    ui->quickWidget_2->rootContext()->setContextProperty("serial", serial);
    ui->quickWidget_2->setResizeMode(QQuickWidget::SizeRootObjectToView);
    //3 cpp 与 qml信号连接
    QObject* obj = ui->quickWidget_2->rootObject();
    if(QMetaObject::invokeMethod(obj, "slotOpenSerial", Qt::DirectConnection, Q_ARG(bool, true), Q_ARG(QString, "")))
        connect(serial, SIGNAL(openMsg(bool,QString)), obj, SIGNAL(slotOpenSerial(bool,QString)));
}

解决办法:先设置串口对象在根节点中的name,再将qml添加到quickWidget

cpp 复制代码
{
    //1
    serial = new SerialPort;
    ui->quickWidget_2->rootContext()->setContextProperty("serial", serial);
    ui->quickWidget_2->setResizeMode(QQuickWidget::SizeRootObjectToView);
    //2
    ui->quickWidget_2->setSource(QUrl("qrc:/Form02.qml"));
    //3 cpp 与 qml信号连接
    QObject* obj = ui->quickWidget_2->rootObject();
    if(QMetaObject::invokeMethod(obj, "slotOpenSerial", Qt::DirectConnection, Q_ARG(bool, true), Q_ARG(QString, "")))
        connect(serial, SIGNAL(openMsg(bool,QString)), obj, SIGNAL(slotOpenSerial(bool,QString)));
}
相关推荐
我是菜鸟0713号2 天前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_2 天前
QT(4)
开发语言·汇编·c++·qt·算法
lqjun08272 天前
Qt程序单独运行报错问题
开发语言·qt
酷飞飞3 天前
Qt Designer与事件处理
开发语言·qt·命令模式
mkhase3 天前
9.12-QT-基本登陆界面实现
java·jvm·qt
咕噜咕噜啦啦3 天前
Qt之快捷键、事件处理、自定义按键——完成记事本项目
开发语言·qt
Quz3 天前
QML Charts组件之折线图的鼠标交互
qt
眠りたいです3 天前
基于脚手架微服务的视频点播系统-数据管理与网络通信部分的预备工作
c++·qt·ui·微服务·云原生·架构·媒体
bikong73 天前
Qt/C++,windows多进程demo
c++·windows·qt
油炸自行车3 天前
【Qt】Window环境下搭建Qt6、MSVC2022开发环境(无需提前安装Visual Studio)
qt·visual studio·qt6·msvc2022·qt creator 17.0