PyQt4: 读取QLineEdit/QTextEdit中的文本并通过点击按钮实现文本转换成一些函数

PyQt4: Read texts in QLineEdit/QTextEdit and implement the text change into some functions by clicking a button

我想通过在小部件中输入一些文本来更改函数中的一些值。我不确定我是否应该使用 QLineEdit 或 QTextEdit,因为我已经阅读了一些文档并且他们似乎都能够做到这一点。我有一些示例代码如下。

import sys
import PyQt4
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Widget(QWidget):
    def __init__(self, parent= None):
        super(Widget, self).__init__(parent)
        layout = QGridLayout()

        self.setLayout(layout)

        btn = QPushButton('Push')
        layout.addWidget(btn, 0, 0)

        le = QLineEdit()
        layout.addWidget(le, 0, 1)


    def someFunc(self):
        print () ## should print texts entered in le 


app = QApplication(sys.argv)
widget = Widget()
widget.show()
app.exec_()

正如您在上面看到的,我希望 "someFunc" 方法通过单击 "Push" 按钮来打印放入文件中的任何文本。

如果有人知道如何解决这个问题,请告诉我谢谢!!

您需要将按钮的 clicked 信号连接到 someFunc,并将 le 设置为主 window 的属性(以便您可以访问它稍后)。

您的 Widget class 因此应该如下所示:

class Widget(QWidget):
    def __init__(self, parent= None):
        super(Widget, self).__init__(parent)
        layout = QGridLayout()

        self.setLayout(layout)

        btn = QPushButton('Push')
        # connect the signal to the slot
        btn.clicked.connect(self.someFunc)
        layout.addWidget(btn, 0, 0)

        # set an attribute
        self.le = QLineEdit()
        self.le.textChanged.connect(self.otherFunc)
        layout.addWidget(self.le, 0, 1)

    def someFunc(self):
        # use the attribute to get the text
        print('button-clicked:', self.le.text())

    def otherFunc(self, text):
        print('text-changed:', text)