更改 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)
这种语法有几个优点:
- 更清晰
- 它更简洁,更易读
- 它提供了更多的错误检查,因为如果信号不存在,它会引发错误.使用旧语法不会引发错误,但信号也未连接,结果就是您看到的行为.