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)));
}
相关推荐
JCBP_1 天前
QT(1)
开发语言·汇编·c++·qt
可峰科技1 天前
qt配置ros2环境,简单版本
开发语言·qt
谱写秋天1 天前
VSCode+Qt+CMake详细地讲解
c++·ide·vscode·qt·编辑器
ajassi20001 天前
开源 C++ QT Widget 开发(六)通讯--TCP调试
c++·qt·开源
Forward♞1 天前
Qt——网络通信(UDP/TCP/HTTP)
开发语言·c++·qt
老赵的博客2 天前
QT的项目pro qmake编译
开发语言·qt
WALL-EC2 天前
Qt工具栏中图标槽函数没有响应的问题分析
开发语言·qt·osgearth
春蕾夏荷_7282977253 天前
qt ElaWidgetTools第一个实例
开发语言·qt
韭菜钟3 天前
在Qt中用cmake实现类似pri文件的功能
开发语言·qt·系统架构
韭菜钟3 天前
Qt从qmake迁移到cmake的记录
开发语言·qt