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)));
}