关于直接控制台到Pyqt GUI的两个问题

2024-10-02 00:35:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将控制台定向到Pyqt GUI

我搜索stackoverflow,找到答案

Print out python console output to Qtextedit

代码如下所示

class Stream(QtCore.QObject):
    newText = QtCore.pyqtSignal(str)

    def write(self, text):
        self.newText.emit(str(text))

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("PyQT tuts!")
        self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
        self.home()

        sys.stdout = Stream(newText=self.onUpdateText)

    def onUpdateText(self, text):
        cursor = self.process.textCursor()
        cursor.movePosition(QtGui.QTextCursor.End)
        cursor.insertText(text)
        self.process.setTextCursor(cursor)
        self.process.ensureCursorVisible()

    def __del__(self):
        sys.stdout = sys.__stdout__

我有两个问题

  1. 为什么定义了def write(self, text),但没有使用

  2. Stream(newText=self.onUpdateText)中的参数是什么意思,我的pycharm给了我一个warn意外参数


Tags: textselfstreamdefstdoutsysprocesscursor
1条回答
网友
1楼 · 发布于 2024-10-02 00:35:22

1。为什么定义了def write(self,text)但未使用

要理解为什么要实现write方法,只需阅读^{}内置的文档:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

Changed in version 3.3: Added the flush keyword argument.

(强调矿山)

如图所示,“打印”功能实现了一种逻辑,可以通过write方法将文本以简单的文字(添加sep、end等)写入默认为sys.stdout的文件中

因此,目标不是在sys.stdout设备上写入,而是重定向文本,因此必须修改该方法,以便它通过newText信号发送信息

2。流中的参数(newText=self.onUpdateText)是什么意思,my pycharm给了我一个意外的参数。

默认情况下,QObject可以接收QProperty初始值的KWARG,并连接qsignals。在这种情况下,这是第二种选择,所以

sys.stdout = Stream(newText=self.onUpdateText)

相等于

sys.stdout = Stream()
sys.stdout.newText.connect(self.onUpdateText)

PyHoog表示警告“意外参数”,因为它所指示的逻辑是用C++实现的(通过SIP),IDE无法处理它们。跳过它,因为它只是IDE的一个限制

相关问题 更多 >

    热门问题