为什么不能将生成器功能用作插槽?

时间:2019-09-03 15:45:51

标签: python generator pyside2 qt-slot

我正在尝试遍历PySide2应用程序中的列表。因此,每次按下“下一步”按钮时,都会从列表中返回并显示下一项。我可以跟踪列表中最近读取的条目的索引,并在每次调用插槽时手动增加索引,但是我认为将插槽转换为生成器函数可能更优雅。但这是行不通的。

下面是最小的(不是)工作示例。

import sys
from PySide2.QtWidgets import QApplication, QPushButton
from PySide2.QtCore import SIGNAL, QObject

def func():
    stringEntries=["One", "Two", "Three"]
    for item in stringEntries:
        # In the application this sets the values of a numpy array 
        # and fires a signal which updates a matplotlib canvas but meh, whatever
        print("func ", item, " has been called!")
        # This sort of works without the following yield statement
        yield

app = QApplication(sys.argv)
button = QPushButton("Next")
QObject.connect(button, SIGNAL ('clicked()'), func)
button.show()                                                                                             

sys.exit(app.exec_())

我有点希望每次按下“下一步”按钮时都将打印不同的字符串,但是相反,它只是坐在那里嘲笑我...

请问有人能指出我根本上误会了吗?

1 个答案:

答案 0 :(得分:1)

@jasonharper在注释中指出,每次按下按钮会产生问题时,您正在创建一个新的迭代器,一种可能的解决方案是创建一个将迭代器作为属性的类,并使用__call__对其进行查看的方法,以使其简单而优雅,我创建了一个装饰器:

from PySide2.QtCore import QObject
from PySide2.QtWidgets import QApplication, QPushButton


class decorator:
    def __init__(self, f):
        self._f = f
        self._iterator = None

    def __call__(self, *args, **kwargs):
        if self._iterator is None:
            self._iterator = self._f(*args, **kwargs)
        try:
            return next(self._iterator)
        except StopIteration:
            pass


@decorator
def func():
    stringEntries = ["One", "Two", "Three"]
    for item in stringEntries:
        print("func ", item, " has been called!")
        yield


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    button = QPushButton("Next")
    button.clicked.connect(func)
    button.show()

    sys.exit(app.exec_())