来自另一个 Class Python 3.8 的 PyQt5 insertPlainText

PyQt5 insertPlainText from Another Class Python 3.8

单击“otherWindow”上的“确定”按钮应该会导致 MainWindow 的 QTextEdit 插入文本“WORKS!”。
问题是,它确实执行 print("Print Works"),但是从另一个函数调用时 insertPlainText 似乎什么都不做。
def printText(self, message): 函数本身没有损坏,它按预期工作,您可以通过单击 Main Window 上的“消息”按钮进行验证。

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QPushButton

class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.myLayout = QVBoxLayout()
        self.status = QTextEdit()
        self.status.setStyleSheet("QTextEdit {min-width:500px;min-height:200px;}")
        self.status.insertPlainText("test")

        self.btnYes = QPushButton("other window")
        self.btnPrint = QPushButton("Message")

        self.btnYes.clicked.connect(self.showOtherWindow)
        self.btnPrint.clicked.connect(self.btnPrintClick)
        self.myLayout.addWidget(self.btnPrint)
        self.myLayout.addWidget(self.btnYes)
        self.myLayout.addWidget(self.status)
        self.setLayout(self.myLayout)

    def setMainText(self, message):
        self.status.insertPlainText("test")
    
    def showOtherWindow(self):
        self.otherWindow = otherWindow()
        self.otherWindow.show()

    def btnPrintClick(self):
        self.printText("button clicked")

    def printText(self, message):
        self.status.insertPlainText("\n" + message)
        print("Print Works")


class otherWindow(QWidget):
    def __init__(self):
        super(otherWindow, self).__init__()
        self.button = QPushButton("OK")
        self.layout2 = QVBoxLayout()
        self.button.clicked.connect(self.btnClick)
        self.layout2.addWidget(self.button)

        self.setLayout(self.layout2)
        self.setFixedSize(200,150)

    def btnClick(self):
        MainWindow().printText("WORKS!")
        self.close()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())

它不起作用,因为您在新 window 上设置文本(立即关闭)。

def btnClick(self):
    MainWindow().printText("WORKS!")

当您调用 MainWindow() 时,您实际上是在创建 MainWindow 的 NEW 实例,并且文本实际上已针对该 window 进行了更新,但是你看不到它,因为它在函数 returns.

之后立即被垃圾收集和删除

您需要访问现有实例,或找到与其通信的方式(通常使用信号)。

在下面的示例中,我将对 window 的主要引用添加到 OtherWindow 构造函数,然后访问它的方法:

class MainWindow(QWidget):
    # ...
    def showOtherWindow(self):
        self.otherWindow = OtherWindow(<b>self</b>)
        self.otherWindow.show()


class OtherWindow(QWidget):
    def __init__(self, mainWindow=None):
        super(OtherWindow, self).__init__()
        self.mainWindow = mainWindow
        # ...

    def btnClick(self):
        if self.mainWindow:
            self.mainWindow.printText("WORKS!")
        self.close()

注意:我把OtherWindow class名字大写了,小写名字应该只用于变量和属性。