在 Qt 上使用看门狗更改 QLabel 文本

Changing QLabel text using watchdog on Qt

我正在尝试做的事情:每当在受监视的文件夹中创建一个新文件(使用看门狗)时,更改 QLabel 文本。

问题:当使用以下代码创建新文件时,QLabel 文本不会更新。 (但成功调试打印到控制台)

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        #This starts the watchdog when button pushed        
        self.pushButton_3.clicked.connect(self.start)

看门狗代码

    def start(self): 
        #Monitoring folder           
        path = self.lineEdit_2.text()

        ## Handler to update text when a file is created
        class MyHandler(FileSystemEventHandler):
            def on_created(self, event):
                **##LABEL_5 should be updated when new file created.**                    
                MainWindow.label_5.setText("File Created")

                ## Plan to use QLabel to show image in future          
                #pixmap = QtGui.QPixmap("path of Image")   
                #self.label_5.setPixmap(pixmap) 

        event_handler = MyHandler()
        observer = Observer()
        observer.schedule(event_handler, path, recursive=True)
        observer.start()

问题的原因是 on_created 是在辅助线程中调用的,Qt 不允许从主线程以外的另一个线程更新 GUI,因为它的元素不是线程安全的。解决方案是使用信号:

from PySide2 import QtCore, QtWidgets

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, FileSystemEvent


class Bridge(QtCore.QObject):
    created = QtCore.Signal(FileSystemEvent)


class Handler(FileSystemEventHandler):
    def __init__(self):
        super().__init__()
        self.bridge = Bridge()

    def on_created(self, event):
        self.bridge.created.emit(event)


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
        self.setCentralWidget(self.label)

    def handle_created(self, event):
        self.label.setText(f"created {event.src_path}")
        print(event.event_type)


def main():
    app = QtWidgets.QApplication()

    path = "/path/of/directory"

    mainwindow = MainWindow()
    mainwindow.resize(640, 480)
    mainwindow.show()

    handler = Handler()
    handler.bridge.created.connect(mainwindow.handle_created)

    observer = Observer()
    observer.schedule(handler, path, recursive=True)
    observer.start()

    app.exec_()


if __name__ == "__main__":
    main()