如何在不停止PyQt5应用程序的情况下运行生成器循环?

2024-04-24 08:09:06 发布

您现在位置:Python中文网/ 问答频道 /正文

My Generator Code

def search(query):
    dir_path = os.path.realpath("C:/")
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            if query.lower() in str(file).lower():
                yield (root, file)
        for directory in dirs:
            if query.lower() in str(directory).lower():
                yield (root, directory)

I want to be able to fetch the results, showing them and run my application simultaneously.

When I do this it hangs the program till the loop is over then show the results

def pushButtonFunc():
    text = self.LocalSearchBar.text()
    newWindow = QtWidgets.QDialog(ProjectOSP)
    newWindow.resize(1201, 861)
    listWidget = QtWidgets.QListWidget(newWindow)
    for root, file in search(text):
        ite = QtWidgets.QListWidgetItem(file)
        listWidget.addItem(ite)```

Tags: thepathtextinforsearchdefdir
1条回答
网友
1楼 · 发布于 2024-04-24 08:09:06

可能的修复方法:

  1. 最简单的方法是调用^{}。它在mainloop上迭代一次,可以从同一线程中的任何位置调用
  2. 另一个解决方案是以某种方式重构代码,使其仅在每个mainloop迭代中执行一次迭代。即使您的大部分工作与GUI有关,这也可以正常工作
  3. 第三种解决方案是将大部分工作分解成一个单独的QThread,然后使用Qt的信号和插槽将数据发送到GUI线程。如果与GUI更改相关的工作很少,这一点尤其有用

最后两个选项中哪一个是最好的,这在很大程度上取决于你的应用程序、你的特定用例,以及更多的代码,而不是方便地链接到这里。这真的是一个只有你才能打的电话

相关问题 更多 >