multiprocessing manager.list inheritance with a pyqt5 signal

谁说胖子不能爱 提交于 2020-07-23 07:59:06

问题


I have a shared list between processors. this list, when change size from different processsor, it runs a function in the main processor to modify a QWidget. Since I can't add somthing to a QWidget from another process, I need the slot function to be run in the main processor. Therefore, I need a a slot function activated when a list changed size. @musicamante did a very nice job in creating a list subclass, but it is not working with manager().list(). I tried to inherit to multiprocessing.manager but it doesn't work. I applied a simple example to inherit from a BaseProxy, but seems not working. Please find the code below.

from multiprocessing import Manager
from PyQt5 import QtCore
from multiprocessing.managers import BaseManager
from multiprocessing.managers import BaseProxy


class ListProxy(QtCore.QObject):
    resized = QtCore.pyqtSignal(list)

class SignalList(list):
    def __init__(self, *args):
        super().__init__(*args)
        self._proxy = ListProxy()
        self.resized = self._proxy.resized

    def append(self, item):
        super().append(item)
        self.resized.emit(self)

    def extend(self, iterable):
        super().extend(iterable)
        self.resized.emit(self)

    def pop(self, *args):
        item = super().pop(*args)
        self.resized.emit(self)
        return item

    # this is required for slicing -> myList[:] = []
    # you might want to check if the length of the list is actually changed
    # before emitting the signal
    def __setitem__(self, *args, **kwargs):
        super().__setitem__(*args, **kwargs)
        self.resized.emit(self)

    def __delitem__(self, *args, **kwargs):
        super().__delitem__(*args, **kwargs)
        self.resized.emit(self)

    # this is required for concatenation -> myList += iterable
    def __iadd__(self, *args, **kwargs):
        super().__iadd__(*args, **kwargs)
        self.resized.emit(self)
        return self

class DataSetProxy(BaseProxy):
    _exposed_ = ('append', '__len__')

    def append(self, item):
        return self._callmethod('append', item)

    def __len__(self):
        return self._callmethod('__len__')

class MyManager(BaseManager):
    pass

MyManager.register('Mylist', SignalList, DataSetProxy)


@QtCore.pyqtSlot(list)
def onclick(l):
    print('resized', l)


if __name__ == '__main__':
    manager = MyManager()
    manager.start()
    mylist = manager.Mylist()
    mylist.resized.connect(onclick)
    mylist.append('item1')
    mylist.append('item2')
    mylist[:] = []

来源:https://stackoverflow.com/questions/62456074/multiprocessing-manager-list-inheritance-with-a-pyqt5-signal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!