Krishna Raj K Krishna Raj K - 3 months ago 19
C++ Question

qfilesystemwatcher emits directorychanged signal 2 times when file edited

I need to watch a directory in qt. created the connection. but when file edited, the sender emits directory changed signal twice. filechanged signal also emitted at the same time. what is the use of emitting the signal twice? and is there any way to know which file/folder is changed? please help..
here is the connect code

QFileSystemWatcher *watcher = new QFileSystemWatcher;
watcher->addPath("/home/user/directory/");
connect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(directoryChangedHandler(QString)));


and function

void MainWindow::directoryChangedHandler(QString path)
{
QMessageBox::information(0, "Directory Changed", "Directory Changed at " + path);
}

Answer

I figured out the problem. The normal editors removes and writes the file again from the disk. So two signals for deleted file and added file. I tried editing the file using nano editor in Ubuntu. It does not emits any directoryChanged signal but emits the fileChanged signal. So that means it does not removes and adds the file, but edits the same file. One more thing that helps this conclusion is, while using the normal editor, the path is removed from the watcher. That means, the file doesn't exist for a while. I have to add that path manually again. Which is not happening while using nano. Since I wrote the code to add the path again, it shows the error "QFileSystemWatcher: failed to add paths: /home/user/directory/file". Because the path is already in the watcher.