我创建了一个简单的观察者并添加了一条路径。我将观察者的信号连接到我的方法:
void CssSetter::watchIfNeeded(const QString& newPath)
{
if(watcher==nullptr) {
watcher = new QFileSystemWatcher(this);
connect(watcher, &QFileSystemWatcher::fileChanged, this, &CssSetter::cssFileChanged);
}
watcher->addPath(newPath);
}
回调如下所示:
void CssSetter::cssFileChanged(const QString& path)
{
qDebug()<<"CSS "<<path<<" changed!";
QFileInfo css_file(path);
qDebug()<<"[CSS] Watcher: "<<path<<(css_file.isFile()?" exists!":" doesn't exist!");
// Should update CSS file, but fails because it also has `.exists()` checks inside
setCSSFromPath(path);
}
输出是:
csssetter.cpp:81 (void CssSetter::cssFileChanged(const QString&)): CSS "/storage/extSdCard/w98.css" changed!
csssetter.cpp:84 (void CssSetter::cssFileChanged(const QString&)): [CSS] Watcher: "/storage/extSdCard/w98.css" doesn't exist!
csssetter.cpp:24 (void CssSetter::setCSSFromPath(QFile&)): [CSS] "/storage/extSdCard/w98.css" doesn't exist!
最后一行来自通常负责加载文件(如果存在)的函数。当我试图覆盖控件时,它不起作用。在文件观察者的回调中读取文件是不可能的。
QFileSystemWatcher
当报告文件已更改时,如何正确读取文件?这是故意的,还是一个错误?