【问题标题】:Changing QLabel text using watchdog on Qt在 Qt 上使用看门狗更改 QLabel 文本
【发布时间】:2021-10-20 20:38:51
【问题描述】:

我正在尝试做的事情:每当在受监控的文件夹中创建新文件(使用 Watchdog)时,更改 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()

【问题讨论】:

    标签: python pyside2 qlabel watchdog


    【解决方案1】:

    问题的原因是 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多