如何在函数结束之前让项目显示在我的 QListWidget 中?

How can I get Items to show in my QListWidget before the end of the function?

我希望我的 QListWidget 在添加新项目时更新它,但它只会在功能结束后更新所有项目。我试过使用 update()repaint(),但都不起作用。实际上,我不得不在 Widget 本身上使用 repaint() 才能让它在结束前显示,但是 none 的项目确实如此。这是要添加的第一项的简要视图:

def runPW10(self):
    self.PWList.setVisible(True)
    self.PWList.setEnabled(True)

    # This repaint() has to be here for even the List to show up
    self.PWList.repaint()

    ....

    self.PWList.addItem('Executing Change Password Tool')

    # This does not help
    self.PWList.repaint()

    ....

该功能还有很多,但它很长,这应该包括它所需要的。如果需要更多,请告诉我。

我做错了什么导致这个列表在添加项目时没有更新?

添加QApplication.processEvents().

QCoreApplication.processEvents (QEventLoop.ProcessEventsFlags flags = QEventLoop.AllEvents)

Processes all pending events for the calling thread according to the specified flags until there are no more events to process.

You can call this function occasionally when your program is busy performing a long operation (e.g. copying a file).

您的小部件原本会显示但没有响应。要使应用程序响应,请在添加项目时添加 processEvents() 调用。

请记住,这会对性能产生很大影响。这让整个应用程序循环执行,包括任何排队的事件。 不要将此添加到对性能敏感的循环中。

还要考虑到这允许您的用户与应用程序进行交互,因此请确保可能发生的任何交互都是不允许的,例如 somebutton.enabled(False),或者得到妥善处理,例如 [=14] =] 按钮停止长任务。

请参阅 original C++ docs 了解更多信息,因为 pyqt 是直接端口。

完成Drise关于这一点的回答:

Also consider that this allows your user to interact with the application, so make sure that any interactions that can happen either are not allowed, such as somebutton.enabled(False), or are handled gracefully, like a Cancel button to stop a long task.

您可能希望以这种方式使用 QEventLoop.ExcludeUserInputEvents 标志:QCoreApplication.processEvents(QEventLoop.ExcludeUserInputEvents) 刷新 GUI,同时防止用户激活任何小部件。

QEventLoop.ExcludeUserInputEvents

0x01

Do not process user input events, such as ButtonPress and KeyPress. Note that the events are not discarded; they will be delivered the next time processEvents() is called without the ExcludeUserInputEvents flag.