python - PyQT线程的最简单方法

标签 python qt pyqt thread-safety python-watchdog

我在 PyQt 中有一个 GUI,其函数为 addImage(image_path)。很容易想象,当一个新图像应该被添加到一个 QListWidget 中时它被调用。为了检测文件夹中的新图像,我使用带有 watchdogthreading.Thread 来检测文件夹中的文件更改,然后该线程调用 addImage直接。

这会产生警告,即出于线程安全的原因,不应在 gui 线程之外调用 QPixmap

使这个线程安全的最好和最简单的方法是什么?问线程?信号/槽? QMetaObject.invokeMethod?我只需要将字符串从线程传递到 addImage

最佳答案

您应该使用 Qt 提供的内置 QThread。您可以将文件监控代码放在继承自 QObjectworker 类中,以便它可以使用 Qt Signal/Slot 系统在线程之间传递消息。

class FileMonitor(QObject):

    image_signal = QtCore.pyqtSignal(str)

    @QtCore.pyqtSlot()
    def monitor_images(self):
        # I'm guessing this is an infinite while loop that monitors files
        while True:
            if file_has_changed:
                self.image_signal.emit('/path/to/image/file.jpg')


class MyWidget(QtGui.QWidget):

    def __init__(self, ...)
        ...
        self.file_monitor = FileMonitor()
        self.thread = QtCore.QThread(self)
        self.file_monitor.image_signal.connect(self.image_callback)
        self.file_monitor.moveToThread(self.thread)
        self.thread.started.connect(self.file_monitor.monitor_images)
        self.thread.start()

    @QtCore.pyqtSlot(str)
    def image_callback(self, filepath):
        pixmap = QtGui.QPixmap(filepath)
        ...

关于python - PyQT线程的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37252756/

相关文章:

c++ - 如何创建一个三角形的QWidget?

python - 为 python GUI 应用程序授予 root 权限以在 ubuntu 中运行命令

python - 如何在Python网络浏览器中突出显示文本,例如查找文本

python - raise_(​​) 函数被忽略

python - 具有超过 2 个值的 zip 列表来字典 python

c++ - QAbstractItemModel 中的嵌套操作

Python GUI 编程、许可和理解

python - python可以做高斯拟合和外推吗?

python mechanize forms() 错误

c++ - QGraphicsView/Scene - 项目绘制距离鼠标点击 2 倍