在 c++ 和 qml 中使用多线程

Use multithread in c++ and qml

本文关键字:多线程 qml c++      更新时间:2023-10-16

main.cpp

int main(int argc, char* argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc,argv);
    QQmlApplicationEngine engine;
    BlueToothdevice d;
    engine.rootContext()->setContextProperty("device", &d);
    qDebug()<<"main thread:"<< QThread::currentThreadId();
    engine.load(QUrl(QStringLiteral("qrc:/assets/main.qml")));
    return app.exec();
}

蓝牙设备.h

class BlueToothdevice : public QObject { balabalabala }

蓝牙设备.cpp

balabalabala

主.qml

...
Text {
    id: bloodglucoseText2
    text: device.bdsugar
    font.pixelSize: 6 * dpi
}
...

如何将 main.cpp 中定义的对象"d"移动到另一个线程? 我仍然想在不更改的情况下使用对象"d"。

在Qt类中定义属性和可调用的方法。

// Define the property bdsugar, accessible from Qml
Q_PROPERTY(bdsugar READ getBdSugar WRITE setBdSugar NOTIFY on BdSugarChanged)
// Define the method bdsugar, callable from Qml
Q_INVOKABLE QString bdsugar( return my_bdsugar; ) const;

但是没有必要将对象 d 移动到另一个线程(或者我不明白这个问题(。