azertq azertq - 24 days ago 12
Python Question

PyQt Can't get text from QlineEdit using text()

I have a

QlineEdit
and while recovering text from it using this code:

doc = self.lineEdit_2.text()

def pushButton_7_clicked(doc):
print(doc)

self.pushButton_7.clicked.connect(pushButton_7_clicked)


I get no error, but it prints
False
whether the
QlineEdit
contains text or not.

Answer

The clicked signal (see docs) passes an attribute to the pushButton_7_clicked callback:

void QAbstractButton::clicked(bool checked = false)

This signal is emitted when the button is activated (i.e. pressed down then released while the mouse cursor is inside the button), when the shortcut key is typed, or when click() or animateClick() is called. Notably, this signal is not emitted if you call setDown(), setChecked() or toggle().

If the button is checkable, checked is true if the button is checked, or false if the button is unchecked.

So, when you define the callback, the first argument is that checked boolean.

Calling it doc in the callback definition doesn't make any difference. You're not passing your doc instance, here. What you get here is the checked boolean, which is False all the time.

That's a pure python issue.

a = 12
def b(a):
    print(a)
b(69)

This prints 69, not 12. You're redefining a (doc in your case) in the scope of the function.

Besides, it does not make sense either to write:

doc = self.lineEdit_2.text()

as this executes only once at import time.

You could try something like this. Note you need to put that callback in your object so that it is bound to it and has a reference to itself in self.

class YourObject():

    def pushButton_7_clicked(self, checked):
        print(self.lineEdit_2.text())

    self.pushButton_7.clicked.connect(self.pushButton_7_clicked)