2

I am trying to learn a bit of qt and qml and I want to make a small application which will monitor a local file for changes and change a Text component when changes happen. I based my code on this answer, but even though I am not getting any warning/error during compilation and running, connecting the fileChanged signal of the QFileSystemWatcher to the qml connections elements, does not work, i.e., the text does not change when watchedFile.txt is modified. How can I check whether the signal is received in the qml code?

Here is my code:

C++:

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

    QFileSystemWatcher watcher;
    watcher.addPath(QStringLiteral("qrc:/watchedFile.txt"));

    QQmlApplicationEngine* engine = new QQmlApplicationEngine;
    engine->rootContext()->setContextProperty("cppWatcher", &watcher);
    engine->load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

qml:

import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480

    Text {
        id: text
        text:"TEXT"
    }

    Connections {
        target: cppWatcher
        onFileChanged: {
            text.text = "CHANGED"
        }
    }
}
Community
  • 1
  • 1
Cantfindname
  • 2,008
  • 1
  • 17
  • 30
  • "even though I am not getting any warning/error during compilation and running" absence of warning/error messages does not imply absence of errors. – Jesper Juhl Apr 15 '17 at 13:19

3 Answers3

2

You should try a file that is on your file system. Files in qrc resources are embedded into the executable, they do not change. Not sure what exactly you expect to happen. Other than this, that is the declarative way you do connections to a CPP object.

dtech
  • 47,916
  • 17
  • 112
  • 190
0

As @dtech already noticed,

watcher.addPath(QStringLiteral("qrc:/watchedFile.txt"));

is returning false, because qrc:/ is not recognized by watcher as correct path. And, actually, this path doesn't exist in file system at all, because it's internal resource file embedded in executable.

If you will put the path to the file on the disk, your code works just fine.

Also you definitely should check return result here and do not allow proceed futher, if it returns false.

Something like following will work better here:

if (!watcher.addPath(QStringLiteral("C:/your_path/watchedFile.txt")))
    return 1;
Max Go
  • 2,092
  • 1
  • 16
  • 26
-2

The signal fileChanged is emitted when the file path changes, and not its content.

https://doc.qt.io/qt-5/qfilesystemwatcher.html#fileChanged

Silvano Cerza
  • 954
  • 5
  • 16
  • 1
    Wrong. `This signal is emitted when the file at the specified path is modified, renamed or removed from disk.` – dtech Apr 15 '17 at 13:50