I need to monitor a certain folder and find out whether a new file is added to the folder, after that I ask the user whether they want to print the file out or not. The problem lies with the QFileSystemWatcher, I can't really figure out how to get the name of the file that has been added. I tried this code (see later), but the file_changed function doesn't react to any folder changes. The directory_changed function works.
How can I get the name of the file that has been added and how can I capture the Signal/Boolean, so that when a file is added I can trigger the MessageBox and my System Tray Message (see in code). Thanks a lot and sorry for the poor code, I am new to Qt. And please don't point me to C++ examples, I don't understand them.
import sys
from PyQt4.QtGui import *
from PyQt4 import QtCore
# create a system tray message
class SystemTrayIcon(QSystemTrayIcon):
def __init__(self, parent=None):
QSystemTrayIcon.__init__(self, parent)
#self.setIcon(QIcon.fromTheme("document-save"))
self.setIcon(QIcon("C:\Icon2.ico"))
def welcome(self):
self.showMessage("New PayFile found!", "We found a new PayFile.")
def show(self):
QSystemTrayIcon.show(self)
QtCore.QTimer.singleShot(100, self.welcome)
# QFileSystemWatcher with signals
@QtCore.pyqtSlot(str)
def directory_changed(path):
print('Directory Changed: ', path)
@QtCore.pyqtSlot(str)
def file_changed(path):
print('File Changed: ', path)
'''
# QFileSystemWatcher without signals
def directory_changed(path):
print('Directory Changed: %s' % path)
def file_changed(path):
print('File Changed: %s' % path)
'''
if __name__ == '__main__':
a = QApplication(sys.argv)
# add a folder path here
fs_watcher = QtCore.QFileSystemWatcher(['C:\\Folder'])
# without signals
fs_watcher.directoryChanged.connect(directory_changed)
# this doesn't work, I don't get the name of the added file
fs_watcher.fileChanged.connect(file_changed)
# with signals
#fs_watcher.connect(fs_watcher, QtCore.SIGNAL('directoryChanged(QString)'), directory_changed)
# this doesn't work, I don't get the name of the added file
#fs_watcher.connect(fs_watcher, QtCore.SIGNAL('fileChanged(QString)'), file_changed)
# how can I find out whether a new file has been added ???
if fs_watcher.directoryChanged.connect(directory_changed):
tray = SystemTrayIcon()
tray.show()
print_msg = "Would you like to do something with the file?"
reply = QMessageBox.question(None, 'Print The File', print_msg, QMessageBox.Yes, QMessageBox.No)
if reply == QMessageBox.Yes:
print "I said yes"
# do stuff
# print the file
if reply == QMessageBox.No:
print "No"
sys.exit(a.exec_())