我在 PyQt 中有一个带有函数的 GUIaddImage(image_path)
。很容易想象,当需要将新图像添加到 QListWidget 中时会调用它。为了检测文件夹中的新图像,我使用threading.Thread
with watchdog
检测文件夹中的文件更改,然后该线程调用addImage
直接地。
这会产生警告:QPixmap
出于线程安全的原因,不应在 gui 线程之外调用。
使这个线程安全的最好和最简单的方法是什么? Q线程?信号/槽? QMetaObject.invokeMethod?我只需要从线程传递一个字符串到addImage
.
您应该使用内置的QThread
由 Qt 提供。您可以将文件监控代码放在worker继承自的类QObject
这样它就可以使用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)
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)