ryan9025 ryan9025 - 3 years ago 192
Python Question

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

I want to change some values in a function by entering some text in a widget. I'm not sure whether I should use QLineEdit or QTextEdit, since I have read some documentations and they all seem to be able to do it. I have some sample codes as below.

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_()


As you can see above, I want "someFunc" method to print whatever text is put in the le by clicking the "Push" button.

If anyone knows how to solve this, pls let me know thanks!!

Answer Source

You need to connect the button's clicked signal to the someFunc, and also set le as an attribute of the main window (so you can access it later).

Your Widget class should therefore look like this:

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download