How to capture the Tab key press event with PyQt 4.3
This is my OLD blog. I've copied this post over to my NEW blog at:
http://www.saltycrane.com/blog/2008/01/how-to-capture-tab-key-press-event-with/
You should be redirected in 2 seconds.
Normally, pressing the TAB key changes focus among widgets.
However, I would like to use the TAB key for other purposes
(e.g. tab completion).
To gain control of the TAB key press event, I need to subclass
my widget and reimplement the QObject.event()
event handler.
I don't need to re-write the entire event handler. I only need to process
TAB key press events. I will pass all other events to the default
event handler. The example below subclasses the QLineEdit
widget and reimplements the event()
method. Pressing the
TAB key inside this new widget prints out the text "tab pressed"
inside a second QLineEdit
box.
The Events and Event Filters Trolltech QT documentation has a good explanation of how this works. My example shows how to use Python and PyQt instead of C++.
import sys from PyQt4.QtCore import * from PyQt4.QtGui import * #################################################################### def main(): app = QApplication(sys.argv) w = MyWindow() w.show() sys.exit(app.exec_()) #################################################################### class MyWindow(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) # create objects self.la = QLabel("Press tab in this box:") self.le = MyLineEdit() self.la2 = QLabel("\nLook here:") self.le2 = QLineEdit() # layout layout = QVBoxLayout() layout.addWidget(self.la) layout.addWidget(self.le) layout.addWidget(self.la2) layout.addWidget(self.le2) self.setLayout(layout) # connections self.connect(self.le, SIGNAL("tabPressed"), self.update) def update(self): newtext = str(self.le2.text()) + "tab pressed " self.le2.setText(newtext) #################################################################### class MyLineEdit(QLineEdit): def __init__(self, *args): QLineEdit.__init__(self, *args) def event(self, event): if (event.type()==QEvent.KeyPress) and (event.key()==Qt.Key_Tab): self.emit(SIGNAL("tabPressed")) return True return QLineEdit.event(self, event) #################################################################### if __name__ == "__main__": main()
No comments:
Post a Comment