我需要监控某个文件夹并找出是否有新文件添加到该文件夹中,之后我会询问用户是否要打印该文件。问题在于QFileSystemWatcher,我无法弄清楚如何获取已添加的文件的名称。我尝试了这段代码(见后文),但file_changed函数不会对任何文件夹更改做出反应。 directory_changed函数有效。
如何获取已添加文件的名称以及如何捕获Signal / Boolean,以便在添加文件时我可以触发MessageBox和我的系统托盘消息(参见代码)。非常感谢,对于糟糕的代码感到抱歉,我是Qt的新手。请不要指向C ++示例,我不理解它们。
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_())
答案 0 :(得分:2)
文件系统观察程序仅通知您目录已更改,而其中已更改。收到通知后,您必须迭代目录中的项目,并确定是否发生了一些有趣的事情。
可能会发现QFileSystemModel
会更有用,因为当目录获得新成员时它会发出rowAdded
信号。它已经迭代了目录成员并确定了文件系统观察者限制的变化 - 如果你直接使用QFileSystemWatcher
,它几乎可以做你需要做的事情。