这是我的示例程序,我在行编辑中设置文本后,我想用键盘输入关键字将我的光标位置改为一行编辑到另一行。因为这样我写了按键事件但这个函数只执行一个行编辑。任何人都可以帮帮我。谢谢你。
以下是我的示例代码:
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()
一个可能的解决方案是使用eventFilter来监听小部件的事件,因此检查它是否是应用您指示的逻辑的focusWidget:
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_())