首页 > 解决方案 > 如何使 addItem() 添加的文本立即出现在 QDialog 窗口中?

问题描述

最近我编写了这个程序,其中我有一个带有按钮的 QMainWindow 和一个在按下按钮时打开的 QDialog。我还有一个 [text] (它写在 infoWindow 类之上),我希望它逐字出现在 QDialog 上,但现在随着我的程序完成工作,它一起出现。我搜索了很多,但找不到我正在搜索的内容。所以,如果你能告诉我一些让我的 [文本] 逐字出现的方法,那就太棒了:)))

这是我的代码

import time , sys

from PyQt5 import QtWidgets

from PyQt5 import uic

from PyQt5.QtWidgets import QTextBrowser


text = ["Lorem ", "Ipsum", " is ", "simply", " dummy", " text", " of the printing", " and", " typesetting", " industry"]



class infoWindow(QtWidgets.QDialog):

    def __init__(self):
        super(infoWindow, self).__init__()

        uic.loadUi(r"window_design\info_window.ui", self)
        self.setFixedSize(850, 500)

    def textAdd(self):
        self.show()
        for word in text:
            self.infoList.addItem(word)
            time.sleep(0.2)


class main(QtWidgets.QMainWindow):

    def __init__(self):
        super(main, self).__init__()

        uic.loadUi(r"window_design\main.ui", self)
        self.info_window = infoWindow()
        self.setFixedSize(850, 500)
        self.pushButton.clicked.connect(self.info_window.textAdd)


if __name__ == '__main__':
    my_app = QtWidgets.QApplication(sys.argv)

    window = main()
    window.show()

    sys.exit(my_app.exec())

标签: pythonpyqt5

解决方案


GUI 系统是事件驱动的,这意味着控制必须始终尽快返回到应用程序主线程,以允许正确的 UI 更新和用户交互。使用阻塞函数,如 for 循环和sleep,将阻止所有这些,因此结果是接口仅在函数返回时更新:不仅您必须等到所有睡眠都过期,而且您还将仅查看最终结果(一次显示所有项目)。

解决方案是使用 QTimer,它可以确保将控制权正确地返回给应用程序,并在需要时执行函数而不会阻塞任何东西。

在这种情况下,您可以复制列表并定期从中弹出元素,直到列表为空:

class infoWindow(QtWidgets.QDialog):
    def __init__(self):
        super(infoWindow, self).__init__()
        uic.loadUi(r"window_design\info_window.ui", self)
        self.setFixedSize(850, 500)
        self.wordList = text[:]

    def textAdd(self):
        self.show()
        self.nextWord()

    def nextWord(self):
        if not self.wordList:
            return
        self.infoList.addItem(self.wordList.pop(0))
        QtCore.QTimer.singleShot(200, self.nextWord)

推荐阅读