简体   繁体   English

PyQt无法使用text()从QlineEdit获取文本

[英]PyQt Can't get text from QlineEdit using text()

I have a QlineEdit and while recovering text from it using this code: 我有一个QlineEdit ,并使用以下代码从中恢复文本时:

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. 我没有收到任何错误,但是无论QlineEdit是否包含文本,它都会打印False

The clicked signal (see docs ) passes an attribute to the pushButton_7_clicked callback: clicked信号(请参阅docs )将属性传递给pushButton_7_clicked回调:

void QAbstractButton::clicked(bool checked = false) 无效QAbstractButton :: clicked(布尔检查=假)

This signal is emitted when the button is activated (ie 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. 当激活按钮时(即,当鼠标光标位于按钮内部时,按下然后释放),键入快捷键或调用click()或animateClick()时,将发出此信号。 Notably, this signal is not emitted if you call setDown(), setChecked() or toggle(). 值得注意的是,如果您调用setDown(),setChecked()或toggle(),则不会发出此信号。

If the button is checkable, checked is true if the button is checked, or false if the button is unchecked. 如果按钮是可检查的,则如果按钮被选中,则true,否则为false。

So, when you define the callback, the first argument is that checked boolean. 因此,定义回调时,第一个参数是checked布尔值。

Calling it doc in the callback definition doesn't make any difference. 在回调定义中将其称为doc并没有任何区别。 You're not passing your doc instance, here. 您没有在此处传递文档实例。 What you get here is the checked boolean, which is False all the time. 您在这里得到的是checked布尔值,始终为False

That's a pure python issue. 那是一个纯python问题。

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. 这将打印69,12,没有你重新定义adoc在功能的范围,你的情况)。

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 . 请注意,您需要将该回调放入对象中,以便将其绑定到对象并在self引用自身。

class YourObject():

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM