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()
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)
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?
The problem is that the signal is not textChanged(bool)
because it takes a string argument, so it should probably be: 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)
This syntax has several advantages:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With