如何解决来自另一类Python 3.8的PyQt5 insertPlainText
单击“ otherWindow”上的“ OK”按钮应使MainWindow的QTextEdit插入文本“ WORKS!”。
问题是,它确实执行了print("Print Works")
,但是从另一个函数调用时,insertPlainText似乎什么也不做。def printText(self,message):
函数本身并未损坏,它按预期运行,可以通过单击主窗口上的“消息”按钮进行验证。
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_())
解决方法
这不起作用,因为您是在新窗口(立即关闭)上设置文本的。
def btnClick(self):
MainWindow().printText("WORKS!")
调用MainWindow()
时,实际上是在创建MainWindow的 NEW 实例,并且该文本实际上已针对该窗口进行了更新,但无法原样看到函数返回后立即清除垃圾并删除。
您需要访问现有实例,或找到一种与之通信的方法(通常使用信号)。
在下面的示例中,我将对主窗口的引用添加到OtherWindow
构造函数中,然后再访问它的方法:
class MainWindow(QWidget):
# ...
def showOtherWindow(self):
self.otherWindow = OtherWindow(self)
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
类名大写,小写名称仅应用于变量和属性。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。