Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an action when the QLineEdit text is changed (programmatically)

Tags:

python

pyqt

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?

like image 260
Matteo NNZ Avatar asked Mar 20 '14 11:03

Matteo NNZ


1 Answers

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:

  • It is clearer
  • It's less verbose and more readable
  • It provides more error checking because if the signal doesn't exist it raises an error. With the old syntax no error is raised, but the signal isn't connected either and the result is the behaviour you have seen.
like image 62
Bakuriu Avatar answered Sep 18 '22 13:09

Bakuriu