gpt4 book ai didi

python - PyQT线程的最简单方法

转载 作者:太空狗 更新时间:2023-10-29 20:36:29 28 4
gpt4 key购买 nike

我在 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com