这是我在行编辑中设置文本后的示例程序,我想使用键盘输入关键字将光标位置从一行编辑更改为另一行。因此,我编写了按键事件,但此功能仅对一个执行行编辑。任何人都可以帮助我。谢谢您。
下面是我的示例代码:
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_())
关于python - 如何使用键盘上的Enter关键字将光标从一行编辑移至另一行编辑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55121511/