[PyQt] synced line edits

Hans-Peter Jansen hpj at urpla.net
Fri Sep 24 22:37:19 BST 2010


On Friday 24 September 2010, 22:58:10 Eric Frederich wrote:
> I'm having some trouble trying to figure out how to get two line edits to
> constantly be in sync including cursor position.
> I'm sure its simple, or a matter of creating the right connections, but I
> can't seem to figure it out.
> I'm hooking two line edits textChagned signal up to the other's setText
> slot.
>
> Thankfully PyQt (or Qt)'s setText is smart enough to check whether the
> text actually changed before emitting another signal and not getting
> stuck in an infinite loop.

You're a lucky man.

> The problem seems to be that setText on a QLineEdit doesn't do a similar
> check before changing the cursor position.
>
> I'd like to get two line edits synced up so that I can insert text in the
> beginning, middle, or end of the string but after any letter gets typed
> the cursor goes to the end of the string.

How about this:

#!/usr/bin/env python

from PyQt4.QtCore import *
from PyQt4.QtGui  import *

class LineEdit(QLineEdit):
    def setText(self, text):
        pos = self.cursorPosition()
        super(LineEdit, self).setText(text)
        self.setCursorPosition(pos)
    
class MyForm(QDialog):
    def __init__(self, parent=None):
        super(MyForm, self).__init__(parent)
        layout = QVBoxLayout()
        le1 = LineEdit()
        le2 = LineEdit()
        layout.addWidget(le1)
        layout.addWidget(le2)
        self.setLayout(layout)
        le1.textChanged.connect(le2.setText)
        le2.textChanged.connect(le1.setText)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    mf = MyForm()
    mf.show()
    sys.exit(app.exec_())


Cheers,
Pete

> Any help is appreciated.
>
> Thanks,
> ~Eric
>
> #!/usr/bin/env python
>
> from PyQt4.QtCore import *
> from PyQt4.QtGui  import *
>
> class MyForm(QDialog):
>     def __init__(self, parent=None):
>         super(MyForm, self).__init__(parent)
>         layout = QVBoxLayout()
>         le1 = QLineEdit()
>         le2 = QLineEdit()
>         layout.addWidget(le1)
>         layout.addWidget(le2)
>         self.setLayout(layout)
>
>         self.connect(le1, SIGNAL("textChanged(QString)"), le2.setText)
>         self.connect(le2, SIGNAL("textChanged(QString)"), le1.setText)
>
> if __name__ == '__main__':
>     import sys
>     app = QApplication(sys.argv)
>     mf = MyForm()
>     mf.show()
>     sys.exit(app.exec_())


More information about the PyQt mailing list