gpt4 book ai didi

python - PyQt : Set text in a QLabel adding letter by letter

转载 作者:太空宇宙 更新时间:2023-11-04 05:56:17 25 4
gpt4 key购买 nike

我试图通过一个接一个地添加字母来创建一个显示 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_())

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

最佳答案

您可以使用 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_())

关于python - PyQt : Set text in a QLabel adding letter by letter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27608011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com