【问题标题】:PyQt: Set text in a QLabel adding letter by letterPyQt:在 QLabel 中设置文本逐个字母添加
【发布时间】:2014-12-22 18:00:24
【问题描述】:

我正在尝试创建一个应用程序,通过逐一添加字母来显示QLabel(或QTextEdit)的内容(就像应用程序正在编写它们一样)。

这是python中的一个例子:

import os, time

def write(text, time):
    base = ""
    for char in text:
        os.system("clear")
        base += char
        print base
        time.sleep(time)

def main():
    text = "this is a test"
    write(text, 0.05)

这是我的 PyQt 代码:

from PyQt4 import QtCore, QtGui
import sys

class Example(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)

        self.initUi()

        text = "this is a test"
        self.write(text, 50)

    def initUi(self):
        self.setGeometry(300, 300, 250, 150) 
        self.show()

        self.label = QtGui.QLabel(self)
        self.label.move(120, 60)

    def write(self, text, msec):
        base = ""
        for char in text:
            base += char
            self.label.setText(base)
            QtCore.QThread.msleep(msec)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

显然,这段代码不起作用 - 但我不知道如何做这个“简单”的事情。

【问题讨论】:

  • 您是否尝试过在每次睡眠前添加self.label.repaint()
  • 我通过使用 processEvent 部分解决了我的问题。不幸的是,我真正需要的是一种不会冻结主窗口的睡眠方法。这个应用程序必须做接下来的事情:显示(“写作”)“欢迎” -> 做一些工作 -> 清除标签内容 -> 在同一标签中显示结果 -> 做其他任务 -> 等等。希望有人可以帮我。谢谢!

标签: python text pyqt4 qlineedit


【解决方案1】:

您可以使用QTimer 来执行此操作:

import sys
from PyQt4 import QtCore, QtGui

class Example(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.label = QtGui.QLabel(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.label)
        self._text = 'this is a test'
        self._index = 0
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.handleTimer)
        self.timer.start(200)

    def handleTimer(self):
        self._index += 1
        self.label.setText(self._text[:self._index])
        if self._index > len(self._text):
            self.timer.stop()

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.setGeometry(300, 300, 250, 150)
    ex.show()
    sys.exit(app.exec_())

【讨论】:

  • 谢谢你,ekhumoro!就像我上面说的,我已经用 processEvents() 方法解决了这个问题,但我真正的问题是另一个问题(我无法很好地解释我需要什么)。无论如何,您的代码对我非常有用,它是我提出的问题的正确答案。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 2014-12-10
  • 1970-01-01
相关资源
最近更新 更多