我已经创建了一个自定义输出流,并且在它的帮助下我将输出重定向到python QT TextEdit,但是在文本编辑中它显示了重定向的所有输出,我想知道是否有某种方式显示一次只有最后一行。 例如,它显示从1到99的for循环数据。文本编辑显示从1到99的所有迭代的数据。我希望它应该只显示最后一行,即可能是2然后是3而儿子则是99。
请参阅以下示例代码:
import sys
import os
from PyQt4 import QtGui,QtCore
from threading import Thread
class EmittingStream(QtCore.QObject):
textWritten = QtCore.pyqtSignal(str)
def write(self, text):
self.textWritten.emit(str(text))
class gui(QtGui.QMainWindow):
def __init__(self):
# ...
super(gui, self).__init__()
# Install the custom output stream
sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)
self.initUI()
def __del__(self):
# Restore sys.stdout
sys.stdout = sys.__stdout__
def normalOutputWritten(self, text):
cursor = self.textEdit.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
cursor.insertText(text)
self.textEdit.ensureCursorVisible()
def callProgram(self):
for i in range(1,100):
command="echo hi %s"%i
result=os.popen(str(command)).read()
print result
def initUI(self):
self.setGeometry(100,100,300,300)
self.show()
cmd=QtGui.QButtonGroup(self)
self.NoCmd=QtGui.QRadioButton("Best Quality",self)
self.NoCmd.setChecked(True)
self.runCommand = QtGui.QRadioButton("Quality Options",self)
cmd.addButton(self.NoCmd)
cmd.addButton(self.runCommand)
self.lineEdit=QtGui.QLineEdit(self)
self.textEdit=QtGui.QTextEdit(self)
self.textEdit.show()
self.textEdit.setGeometry(20,40,200,200)
self.lineEdit.move(200,0)
self.runCommand.move(100,0)
self.lineEdit.show()
self.NoCmd.show()
self.runCommand.show()
print "changing sys.out"
print "hello"
thread = Thread(target = self.callProgram)
thread.start()
#Function Main Start
def main():
app = QtGui.QApplication(sys.argv)
ui=gui()
sys.exit(app.exec_())
#Function Main END
if __name__ == '__main__':
main()
提前致谢
答案 0 :(得分:2)
每次数字行超过某个限制时,您都可以删除文本编辑的第一行:
def normalOutputWritten(self, text):
cursor = self.textEdit.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
cursor.insertText(text)
# show only the last 10 lines
if self.textEdit.document().lineCount() > 10:
cursor.movePosition(QtGui.QTextCursor.Start)
cursor.select(QtGui.QTextCursor.LineUnderCursor)
cursor.removeSelectedText()
cursor.deleteChar()
self.textEdit.ensureCursorVisible()