0

我需要监视某个文件夹并找出是否将新文件添加到该文件夹​​中,然后询问用户是否要打印该文件。问题出在 QFileSystemWatcher 上,我真的不知道如何获取已添加的文件的名称。我尝试了这段代码(见下文),但 file_changed 函数对任何文件夹更改都没有反应。directory_changed 函数有效。

如何获取已添加文件的名称以及如何捕获信号/布尔值,以便在添加文件时触发 MessageBox 和我的系统托盘消息(参见代码)。非常感谢,对糟糕的代码感到抱歉,我是 Qt 的新手。请不要指给我看 C++ 的例子,我不明白。

 
导入系统
从 PyQt4.QtGui 导入 *
从 PyQt4 导入 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_())

4

1 回答 1

2

文件系统观察器只通知您目录已更改,而不是其中的更改。收到通知后,您必须迭代目录中的项目并确定那里是否发生了有趣的事情。

结果可能QFileSystemModel会更有用,因为它会rowAdded在目录获得新成员时发出信号。尽管文件系统观察者的限制,它已经迭代了目录成员并确定了更改 - 如果您直接使用它,它几乎可以完成您需要做的事情QFileSystemWatcher

于 2015-08-19T15:15:31.297 回答