我想在带有三个按钮的对话框中显示一个日志文件。我可以使用以下代码将每一行附加到textBrowser,但是当我尝试附加整个文本时,GUI会冻结。
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import os
import sys
import time
import UI_logs
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class WorkThread(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def __del__(self):
self.wait()
def run(self):
#Reading and appending the whole text
# logs = open('logs.txt', 'r').read()
# self.emit(QtCore.SIGNAL('update(QString)'), str(logs))
#Reading and appending line by line
logs = open('logs.txt', 'r').readlines()
for line in logs:
self.emit(QtCore.SIGNAL('update(QString)'), str(line))
time.sleep(0.1)
self.terminate()
class Logs(QtGui.QDialog):
def __init__(self, parent=None):
super(Logs, self).__init__(parent)
self.ui = UI_logs.Ui_Dialog()
self.ui.setupUi(self)
self.load_logs()
QtCore.QObject.connect(self.ui.pushButton_3, QtCore.SIGNAL(_fromUtf8("clicked()")), self.clear_logs)
QtCore.QObject.connect(self.ui.pushButton_4, QtCore.SIGNAL(_fromUtf8("clicked()")), self.load_logs)
QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.export)
def display_logs(self, text):
self.ui.textBrowser.append(text)
self.ui.textBrowser.update()
self.ui.textBrowser.moveCursor(QtGui.QTextCursor.End)
def load_logs(self):
self.workThread = WorkThread()
QtCore.QObject.connect(self.workThread, QtCore.SIGNAL("update(QString)"), self.display_logs)
self.workThread.start()
def clear_logs(self):
try:
os.remove('logs.txt')
self.ui.textBrowser.clear()
info_msg = "Your logs file has been deleted."
info_reply = QtGui.QMessageBox.warning(None, 'Logs Notification', info_msg, QtGui.QMessageBox.Ok)
except:
info_msg = "Your logs file can not be deleted."
info_reply = QtGui.QMessageBox.warning(None, 'Logs Notification', info_msg, QtGui.QMessageBox.Ok)
def export(self):
log_text = self.ui.textBrowser.toPlainText()
if log_text:
filename = QtGui.QFileDialog.getSaveFileName(None, 'Export logs as',
'.', 'Text Documents (*.txt)')
if filename:
fname = open(filename, 'w')
fname.write(log_text)
fname.close()
info_msg = "Your logs file has been exported successfully."
info_reply = QtGui.QMessageBox.warning(None, 'Logs Notification', info_msg, QtGui.QMessageBox.Ok)
else:
warning_title = 'Export Warning'
warning_text = 'There is nothing in the logs to export.'
QtGui.QMessageBox.warning(None, warning_title,
warning_text, QtGui.QMessageBox.Ok)
app = QApplication(sys.argv)
app.setApplicationName('MyWindow')
window = Logs()
window.show()
sys.exit(app.exec_())
答案 0 :(得分:0)
尝试使用其中一条注释行:
logs = open('logs.txt', 'r').read()
#logs = logs.encode('utf-8')
#logs = QString(logs)
#logs = unicode(QString(logs))
self.emit(QtCore.SIGNAL('update(QString)'), str(logs))
另外,尝试不转换logs
到字符串:
self.emit(QtCore.SIGNAL('update(QString)'), logs)
我没有import UI_logs
所以我无法测试它,但其中一个应该有用......