[PyKDE] Getting control over the Tab key

Konrad Hinsen hinsen at cnrs-orleans.fr
Thu Oct 24 14:56:00 BST 2002


> Below is a piece of code that works as expected. I don't call
> QWidget::SetFocusPolicy() since QLineEdit does that for me.

Put two of them into a QVBox and the Tab key events disappear:

  import qt
  import sys

  class MyLineEdit(qt.QLineEdit):

      def keyPressEvent(self, event):
	  qt.QLineEdit.keyPressEvent(self, event)
	  if event.key() == qt.Qt.Key_Tab:
	      print "Tab pressed in LineEdit"

  class MyMainWidget(qt.QVBox):

      def __init__(self, parent):
	  qt.QVBox.__init__(self, parent)
	  self.line1 = MyLineEdit(self)
	  self.line2 = MyLineEdit(self)
	  self.installEventFilter(self)

      def keyPressEvent(self, event):
	  qt.QVBox.keyPressEvent(self, event)
	  if event.key() == qt.Qt.Key_Tab:
	      print "Tab pressed in MainWidget"

  app = qt.QApplication(sys.argv)
  mw = MyMainWidget(None)
  app.setMainWidget(mw)
  mw.show()
  app.exec_loop()

Some experiments with an event filter (thanks to all those who pointed
out where the problem was!) showed that in the presence of a QVBox,
every key press generates an Accel event to the QVBox, and the Tab key
is eaten by it (used for switching focus among its children). And some
more research in the Qt documentation brought me to the conclusion
that QVBox automatically adds a QAccel object to the top level window.

Apparently there is no way to remove a QAccel object, but I can add
another one that overrides the Tab key setting. So the final version
that works fine is

  import qt
  import sys

  class MyLineEdit(qt.QLineEdit):

      def keyPressEvent(self, event):
	  qt.QLineEdit.keyPressEvent(self, event)
	  if event.key() == qt.Qt.Key_Tab:
	      print "Tab pressed in LineEdit"

  class MyMainWidget(qt.QVBox):

      def __init__(self, parent):
	  qt.QVBox.__init__(self, parent)
	  self.line1 = MyLineEdit(self)
	  self.line2 = MyLineEdit(self)
	  self.accel = qt.QAccel(self)
	  self.accel.connectItem(self.accel.insertItem(qt.Qt.Key_Tab),
				 self.tabKey)

      def tabKey(self):
	  print "Tab pressed somewhere"
	  print "Focus is on ", self.focusWidget()

      def keyPressEvent(self, event):
	  qt.QVBox.keyPressEvent(self, event)
	  if event.key() == qt.Qt.Key_Tab:
	      print "Tab pressed in MainWidget"

  app = qt.QApplication(sys.argv)
  mw = MyMainWidget(None)
  app.setMainWidget(mw)
  mw.show()
  app.exec_loop()

The good news is that it needs no event filter!

Konrad.




More information about the PyQt mailing list