问题
Hey I am using the same old code for getting all the code outputs PyQT5 QTexBrowser GUI console, but I am also getting next line character ("\n") in all new lines.
Code URL - pipe the output of sys.stdout to text browser in pyqt
Below is the code I am using from above URL -
class Port(object):
def __init__(self, view):
self.view = view
def write(self, *args):
# self.view.append(str([*args]))
# self.view.append(str(*args).rstrip("\n").lstrip("\n"))
self.view.append(*args)
GUI Console Output -
Is there any way to remove "\n"
from the args, Please suggest.
when I used below line, then I was able to see that there is "\n"
in every new args.
self.view.append(str([*args]))
GUI Console Output with visible "\n"
(* Ignore the numbers in lines as first character - that is part of user selection output.)
then I tried to do every possible way to remove like strip(), lstrip() etc, still didn't get success.
Below is the part of code, how I am redirecting run time output to QtextBrowser
self.execution_result = QtWidgets.QWidget()
self.execution_result.setObjectName("execution_result")
self.execution_rslt_saveresult_btn = QtWidgets.QPushButton(self.execution_result)
self.execution_rslt_saveresult_btn.setGeometry(QtCore.QRect(1220, 780, 131, 25))
self.execution_rslt_saveresult_btn.setObjectName("execution_rslt_saveresult_btn")
# ------------------------------------------------------------------------------------------------------#
# Console Output
# ------------------------------------------------------------------------------------------------------#
self.execution_rslt_textbrowser = QtWidgets.QTextBrowser(self.execution_result)
self.execution_rslt_textbrowser.setGeometry(QtCore.QRect(2, 1, 1371, 771))
self.execution_rslt_textbrowser.setObjectName("execution_rslt_textbrowser")
self.execution_rslt_textbrowser.setStyleSheet(
"""QTextBrowser {background-color: #000000;
color: #00FF00;
font: 11pt Courier new;}""")
self.execution_rslt_textbrowser.document().setPlainText(
"-" * 40 + '\n' + " Log starts from below line " + '\n' + "-" * 40)
# ------------------------------------------------------------------------------------------------------#
# Below line is sending run time output to GUI console
# ------------------------------------------------------------------------------------------------------#
sys.stdout = Port(self.execution_rslt_textbrowser)
Please anyone suggest what should I do here to remove "\n"
from the outputlines.
also how to remove error AttributeError: 'port' object has no attribute 'flush'
Below is the working sample code with next line character issue. - For reference/debugging
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class Port(object):
def __init__(self, view):
self.view = view
def flush(self):
pass
def write(self, *args):
# self.view.append(str([*args])) # This line will highlight next line character in console "\n"
self.view.append(*args)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
# MainWindow.setEnabled(True)
MainWindow.resize(1000, 500)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(1000, 500))
MainWindow.setMaximumSize(QtCore.QSize(1000, 500))
MainWindow.setBaseSize(QtCore.QSize(1000, 500))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setMinimumSize(QtCore.QSize(0, 883))
self.centralwidget.setObjectName("centralwidget")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(280, 0, 671, 341))
self.tabWidget.setTabPosition(QtWidgets.QTabWidget.North)
self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)
self.tabWidget.setDocumentMode(False)
self.tabWidget.setTabsClosable(False)
self.tabWidget.setObjectName("tabWidget")
self.execution_result = QtWidgets.QWidget()
self.execution_result.setObjectName("execution_result")
self.execution_rslt_textbrowser = QtWidgets.QTextBrowser(self.execution_result)
self.execution_rslt_textbrowser.setGeometry(QtCore.QRect(1, 1, 681, 321))
self.execution_rslt_textbrowser.setObjectName("execution_rslt_textbrowser")
self.execution_rslt_textbrowser.document().setPlainText(
"-" * 40 + '\n' + " Log starts from below line " + '\n' + "-" * 40)
# ----------------------------------------------------------------------------#
# Console Output Redirection
# ----------------------------------------------------------------------------#
sys.stdout = Port(self.execution_rslt_textbrowser)
# ----------------------------------------------------------------------------#
self.tabWidget.addTab(self.execution_result, "")
self.mainwindow_list = QtWidgets.QListWidget(self.centralwidget)
self.mainwindow_list.setGeometry(QtCore.QRect(20, 30, 241, 301))
self.mainwindow_list.setObjectName("mainwindow_list")
self.mainwindow_list.itemClicked['QListWidgetItem*'].connect(self.qlistoptions)
item = QtWidgets.QListWidgetItem()
font = QtGui.QFont()
font.setPointSize(9)
item.setFont(font)
self.mainwindow_list.addItem(item)
item = QtWidgets.QListWidgetItem()
font = QtGui.QFont()
font.setPointSize(9)
item.setFont(font)
self.mainwindow_list.addItem(item)
item = QtWidgets.QListWidgetItem()
font = QtGui.QFont()
font.setPointSize(9)
item.setFont(font)
self.mainwindow_list.addItem(item)
item = QtWidgets.QListWidgetItem()
font = QtGui.QFont()
font.setPointSize(9)
item.setFont(font)
self.mainwindow_list.addItem(item)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.execution_result), _translate("MainWindow", "Execution Console"))
__sortingEnabled = self.mainwindow_list.isSortingEnabled()
self.mainwindow_list.setSortingEnabled(False)
item = self.mainwindow_list.item(0)
item.setText(_translate("MainWindow", "Item1"))
item = self.mainwindow_list.item(1)
item.setText(_translate("MainWindow", "Item2"))
item = self.mainwindow_list.item(2)
item.setText(_translate("MainWindow", "Item3"))
item = self.mainwindow_list.item(3)
item.setText(_translate("MainWindow", "Item4"))
self.mainwindow_list.setSortingEnabled(__sortingEnabled)
def qlistoptions(self):
print("Inside qlistoptions method : Button Clicked")
# window.hide() ## This to close main window and open new window.
print(self.mainwindow_list.currentRow()) # Will Return Index number of list item
print(self.mainwindow_list.currentItem().text()) # Will Return current selected text from list item
# print("Signal-", self.mainwindow_ok.isChecked())
# Item1
if self.mainwindow_list.currentRow() == 0:
print("Item1 is Clicked!!")
# Item2
elif self.mainwindow_list.currentRow() == 1:
print("Item2 is Clicked!!")
# Item3
elif self.mainwindow_list.currentRow() == 2:
print("Item3 is Clicked!!")
# Item4
elif self.mainwindow_list.currentRow() == 3:
print("Item4 is Clicked!!")
else:
print("Please select any item first!!")
def printText(self, button):
print("Value from printText Method -")
print(button.text())
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
回答1:
The append method adds an additional endline, the solution is to insert the text without adding it:
class Port(object):
def __init__(self, view):
self.view = view
def flush(self):
pass
def write(self, text):
cursor = self.view.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
cursor.insertText(text)
self.view.setTextCursor(cursor)
self.view.ensureCursorVisible()
回答2:
I write with command: sys.stdout.write("Append a line to console!")
, it's all good, nothing redundant.
To delete the flush attribute error, just add to your Port class this override function:
def flush(self):
pass
Tested!
来源:https://stackoverflow.com/questions/63110506/how-to-redirect-python-script-output-to-pyqt5-gui-console-without-any-buttons-c