PDA

View Full Version : QFileSystemWatcher send fileChanged() signal to a qml slot



texasRanger
22nd June 2020, 20:17
Hello,

I have a GUI display that shows data values from an external file. I want to be able to update the display whenever the values in the file change. I'm trying to use QFileSystemWatcher fileChanged() to emit a signal to the SLOT in qml that will update the display. I can't seem to figure out the sending of the signal when the file is read.




//readJSON.h

class readJSON :public QObject
{
Q_OBJECT

public:
readJSON();

public slots:
QString readingJson(const QString &name);

};


//main.cpp

int main(int argc, char *argv[])
{


QCoreApplication::setAttribute(Qt::AA_EnableHighDp iScaling);

QGuiApplication app(argc, argv);

QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);



QFileSystemWatcher watcher;
watcher.addPath("data.json");

readJSON* myGlobal = new readJSON();

engine.rootContext()->setContextProperty("myGlobalObject", myGlobal);


QObject::connect(&watcher, SIGNAL(fileChanged()),
myGlobal, SLOT(updateDisplay()));

engine.load(url);

return app.exec();
}

//main.qml

Window {
visible: true
width: 800
height: 800
title: qsTr("Screen Display")


DisplaysForm {

function callCPP(text) {
var dataOne = myGlobalObject.readingJson(text)
dataOne = parseFloat(dataOne)

return dataOne
}

function updateDisplay() {

var value = callCPP("Engine_Spd")
engSpd_txt.text = value

var value1 = callCPP("Engine_Power")
engPwr_txt.text = value1
}