Here is my sample program after i set the text in line edit, i want to change my cursor position one line edit to another line using with keyboard enter key word.Because of this i wrote key press event but this function is executing only for one line edit.Can any one please help me.Thank you in advance.
Given below is my sample code:
import sys
from PyQt4 import QtGui,QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
box=QtGui.QVBoxLayout(self)
self.lbl1 = QtGui.QLineEdit()
self.lbl1.move(15, 10)
self.lbl2 = QtGui.QLineEdit()
self.lbl2.move(35, 40)
self.lbl3 = QtGui.QLineEdit()
self.lbl3.move(55, 70)
box.addWidget(self.lbl1)
box.addWidget(self.lbl2)
box.addWidget(self.lbl3)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Absolute')
self.show()
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Return:
if self.lbl1.setFocus():
self.lbl2.setFocus()
elif self.lbl2.setFocus():
self.lbl3.setFocus()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
A possible solution is to use an eventFilter to listen to the events of the widgets, so check if it is the focusWidget applying the logic you indicate:
from PyQt4 import QtCore, QtGui
class Singleton(type(QtCore.QObject), type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance=None
def __call__(cls,*args,**kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class EnterFocusManager(QtCore.QObject): #, metaclass=Singleton):
__metaclass__ = Singleton
def __init__(self, parent=None):
super(EnterFocusManager, self).__init__(parent)
QtGui.QApplication.instance().installEventFilter(self)
self._widgets = []
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.KeyPress and obj == QtGui.QApplication.focusWidget():
if event.key() == QtCore.Qt.Key_Return:
f = [(k, v) for k, v in self._widgets if k==obj]
if f:
f[0][1].setFocus(True)
return super(EnterFocusManager, self).eventFilter(obj, event)
@staticmethod
def setEnterOrder(first, second):
EnterFocusManager()._widgets.append((first, second))
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
box = QtGui.QVBoxLayout(self)
self.lbl1 = QtGui.QLineEdit()
self.lbl2 = QtGui.QLineEdit()
self.lbl3 = QtGui.QLineEdit()
box.addWidget(self.lbl1)
box.addWidget(self.lbl2)
box.addWidget(self.lbl3)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Absolute')
self.show()
EnterFocusManager.setEnterOrder(self.lbl1, self.lbl2)
EnterFocusManager.setEnterOrder(self.lbl2, self.lbl3)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())