Skip to content

Instantly share code, notes, and snippets.

@kimmoli
Last active August 29, 2015 14:20
Show Gist options
  • Save kimmoli/762c8d4fb67bc00bd6bd to your computer and use it in GitHub Desktop.
Save kimmoli/762c8d4fb67bc00bd6bd to your computer and use it in GitHub Desktop.
QFileSystemWatcher
void Myclass::start()
{
/* Read the file once */
tmpFileProcess("/tmp/testi");
/* Watch the file */
tmpFileNotifier = new QFileSystemWatcher(QStringList() << "/tmp/testi", this);
/* Connect fileChanged to our slot */
connect(tmpFileNotifier, SIGNAL(fileChanged(QString)), this, SLOT(tmpFileProcess(QString)));
}
void Myclass::tmpFileProcess(QString name)
{
qDebug() << "file" << name << "changed";
QFile fn(name);
if (!fn.open(QIODevice::ReadOnly | QIODevice::Text))
{
/* If file is not found, say so */
_fileContents = "File not found";
/* Tell QML that the property has changed */
emit fileContentsChanged();
return;
}
/* Kinda stupid, read just 100 last characters from file */
_fileContents = QString(fn.readAll().right(100));
fn.close();
/* Tell QML that the property has changed */
emit fileContentsChanged();
}
#include <QFileSystemWatcher>
#include <QFile>
...
Q_OBJECT
...
Q_PROPERTY(QString fileContents READ readFileContents NOTIFY fileContentsChanged())
public:
....
QString readFileContents() { return _fileContents; }
Q_INVOKABLE void start();
private slots:
...
void tmpFileProcess(QString name);
signals:
...
void fileContentsChanged();
private:
...
QFileSystemWatcher *tmpFileNotifier;
QString _fileContents;
};
Button
{
anchors.horizontalCenter: parent.horizontalCenter
text: "start"
onClicked: myclass.start()
}
Label
{
x: Theme.paddingLarge
width: parent.width - 2 * Theme.paddingLarge
text: myclass.fileContents
color: Theme.primaryColor
wrapMode: Text.Wrap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment