更改 QLineEdit 文本时执行操作(以编程方式) [英] Make an action when the QLineEdit text is changed (programmatically)

查看:36
本文介绍了更改 QLineEdit 文本时执行操作(以编程方式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 QLineEdit 编写了以下代码片段,可以通过按下添加文本"按钮进行编辑.

I have written the following code snippet with an QLineEdit that can be edited by pushing the button "Add Text".

import sys
import os
from PyQt4 import QtGui
from PyQt4 import *

class SmallGUI(QtGui.QMainWindow):
    def __init__(self):
        super(SmallGUI,self).__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300,300,300,300)
        self.setWindowTitle('Sample')

        #One input
        self.MyInput = QtGui.QLineEdit(self)
        self.MyInput.setGeometry(88,25,110,20)
        ###############

        QtCore.QObject.connect(self.MyInput,QtCore.SIGNAL("textChanged(bool)"),self.doSomething)

        #Add Text
        self.MyButton = QtGui.QPushButton(self)
        self.MyButton.setGeometry(QtCore.QRect(88,65,110,20))
        self.MyButton.setText('Add Text')
        ###############

        QtCore.QObject.connect(self.MyButton,QtCore.SIGNAL("clicked(bool)"),self.addText)

        self.show()

    def addText(self):
        self.MyInput.setText('write something')

    def doSomething(self):
        print "I'm doing something"

def main():
    app = QtGui.QApplication(sys.argv)
    sampleForm = SmallGUI()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

我想做的是在 QLineEdit 的文本以编程方式更改时执行一个操作,即通过单击添加文本"按钮,执行以下操作:

What I would like to do is to execute an action when the text of the QLineEdit is changed programmatically, i.e. by clicking the button 'Add Text', doing the following:

QtCore.QObject.connect(self.MyInput,QtCore.SIGNAL("textChanged(bool)"),self.doSomething)

我使用信号textChanged"的原因与documentation 说,即当以编程方式更改文本时也会发出此信号,例如,通过调用 setText()."

The reason why I have used the signal "textChanged" is related to what the class documentation says, that is "this signal is also emitted when the text is changed programmatically, for example, by calling setText()."

然而,这不起作用,因为没有执行打印语句.谁能帮我解决这个问题?

However this does not work cause the print statement is not executed. Can anyone help me out with that?

推荐答案

问题在于信号是 not textChanged(bool) 因为它需要一个字符串参数,所以它可能应该是:textChanged(str).

The problem is that the signal is not textChanged(bool) because it takes a string argument, so it should probably bee: textChanged(str).

为避免此类错误,您应该使用新式语法用于连接信号:

To avoid this kind of errors you should use the new-style syntax for connecting signals:

self.MyInput.textChanged.connect(self.doSomething)
# or:
self.MyInput.textChanged[str].connect(self.doSomething)

这种语法有几个优点:

  • 更清晰
  • 它更简洁,更易读
  • 它提供了更多的错误检查,因为如果信号不存在,它会引发错误.使用旧语法不会引发错误,但信号也未连接,结果就是您看到的行为.

这篇关于更改 QLineEdit 文本时执行操作(以编程方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆