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

Two questions about direct console to Pyqt GUI

我想将控制台定向到 Pyqt GUI

然后我搜索Whosebug,找到答案

代码如下

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给我一个警告意外参数

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

要了解为什么要实现 write 方法,只需阅读 print built-in:

的文档

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.

(强调我的)

如前所述,“print”函数实现了一种逻辑,可以通过 write 方法将文本(添加 sep、end 等)写入默认为 sys.stdout 的文件中。

所以objective不是在sys.stdout设备上写入而是重定向文本,所以必须修改该方法,使其通过newText信号发送信息.

2。 Stream(newText=self.onUpdateText) 中的参数是什么意思,我的 pycharm 给我一个警告 Unexpected argument.

默认情况下,QObjects 可以将 kwargs 接收到 qproperties 的初始值,并建立 qsignals 的连接。在这种情况下它是第二个选项,所以

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

等于

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

Pycharm 指示警告“意外的参数”,因为它指示的逻辑是在 C++ 中实现的(通过 SIP)并且 IDE 无法处理它们。跳过它,因为它只是 IDE.

的限制