无法从 PyQT5 文本字段中获取文本
Posted
技术标签:
【中文标题】无法从 PyQT5 文本字段中获取文本【英文标题】:Cant get text from the PyQT5 text field 【发布时间】:2020-01-02 14:56:16 【问题描述】:不明白为什么我从文本字段中得到空字符串,这是我的代码:
class MyMainWindow(QMainWindow, test.Ui_MainWindow):
def __init__(self):
super().__init__()
super().setupUi(self)
self.pushButton.clicked.connect(self.click)
def click(self):
text = self.plainTextEdit.toPlainText()
print('Text: ' + str(text))
print()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QMainWindow()
mainWindow = MyMainWindow()
mainWindow.setupUi(window)
mainWindow.show()
sys.exit(app.exec_())
https://pastebin.com/gpDSysL2
以及QT Designer生成的.py文件:
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget)
self.plainTextEdit.setGeometry(QtCore.QRect(270, 260, 104, 71))
self.plainTextEdit.setObjectName("plainTextEdit")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(270, 350, 75, 23))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
当我单击按钮时,它会打印 empy 字符串 这是我收到>>> Screenshot
的问题的屏幕截图非常感谢您的任何帮助
【问题讨论】:
【参考方案1】:问题在于双重调用 setupUI() 方法:
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QMainWindow()
mainWindow = MyMainWindow()
# mainWindow.setupUi(window) <<< HERE WAS THE PROBLEM, JUST DELETEd THIS LINE AND THATS ALL
mainWindow.show()
sys.exit(app.exec_())
也许有人会有同样的问题
【讨论】:
以上是关于无法从 PyQT5 文本字段中获取文本的主要内容,如果未能解决你的问题,请参考以下文章