本帖最后由 西洛 于 2018-12-21 23:05 编辑
我老师要我做一个连接蓝牙设备的程序,能检测到蓝牙联系的的信息,但是设备信息不能传到qml中,main函数中的数据可以传过去:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <qqmlcontext.h>
#include "datamodel.h"
#include "bluetoothconnect.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
BluetoothConnect btc;
btc.startScan();
QList<QObject*> dataList;
for(int i=0;i<20;i++){
dataList.append(new DataObject("Item"+QString::number(i+1), QString::number(i+1)));
}
qmlRegisterType<BluetoothConnect>("io.BluetoothConnect",1,0,"BluetoothConnect");
engine.rootContext()->setContextProperty
("myModel", QVariant::fromValue(dataList));
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
#include "bluetoothconnect.h"
#include "datamodel.h"
#include <QDebug>
#include <QBluetoothUuid>
#include <QQmlApplicationEngine>
#include <qqmlcontext.h>
static QString devicename;
static QString deviceaId ;
BluetoothConnect::BluetoothConnect():localDevice(new QBluetoothLocalDevice)
{
deviceDiscoveryAgent = new QBluetoothDeviceDiscoveryAgent();
connect(deviceDiscoveryAgent, SIGNAL(deviceDiscovered(QBluetoothDeviceInfo)),this, SLOT(addDevice(QBluetoothDeviceInfo)));
}
BluetoothConnect::~BluetoothConnect()
{
}
void BluetoothConnect::addDevice(const QBluetoothDeviceInfo &info)
{
devicename = QString("%1").arg(info.name());
deviceId =QString("%1").arg(info.address().toString());
qDebug()<<"连接"<<devicename<<endl;
qDebug()<<"连接"<<deviceaId<<endl;
QList<QObject*> dataList;
dataList.append(new DataObject(devicename,deviceId);
engine.rootContext()->setContextProperty("myModel",QVariant::fromValue(btc.getName()))
}
void BluetoothConnect::startScan()
{
deviceDiscoveryAgent->start();
}
|