2425

How to allow tab key pressing event in pyqt5

Question:

Assuming that I have a QPushButton named button, I successfully do the following to allow <strong>click</strong> event:

class UI(object): def setupUi(self, Dialog): # ... self.button.clicked.connect(self.do_something) def do_something(self): # Something here

My question is: how can I call do_something() when the tab key is pressed? For instance, if I have a QlineEdit named tb_id, after entering a value and press tab key, do_something() method should be called in the same way as what clicked does above. How can I do that using pyqt5?

Thank you so much.

Answer1:

To get what you want there are many methods but before pointing it by observing your code I see that you have generated it with Qt Designer so that code should not be modified but create another class that uses that code so I will place the base code:

from PyQt5 import QtCore, QtWidgets class UI(object): def setupUi(self, Dialog): self.button = QtWidgets.QPushButton("Press Me") lay = QtWidgets.QVBoxLayout(Dialog) lay.addWidget(self.button) class Dialog(QtWidgets.QDialog, UI): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setupUi(self) self.button.clicked.connect(self.do_something) @QtCore.pyqtSlot() def do_something(self): print("do_something") if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) w = Dialog() w.resize(640, 480) w.show() sys.exit(app.exec_())

Also, I recommend you read the difference between event and signal in the world of Qt in <a href="https://stackoverflow.com/questions/9323888/what-are-the-differences-between-event-and-signal-in-qt" rel="nofollow">What are the differences between event and signal in Qt</a> since you speak of <em>click event</em> but in the world of Qt one must say <em>clicked signal</em>.

Now if going to the point there are the following options:

<ul><li>Using keyPressEvent:</li> </ul><hr />class Dialog(QtWidgets.QDialog, UI): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setupUi(self) self.button.clicked.connect(self.do_something) @QtCore.pyqtSlot() def do_something(self): print("do_something") def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Tab: self.do_something() <ul><li>Using an event filter:</li> </ul><hr />class Dialog(QtWidgets.QDialog, UI): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setupUi(self) self.button.clicked.connect(self.do_something) @QtCore.pyqtSlot() def do_something(self): print("do_something") def eventFilter(self, obj, event): if obj is self and event.type() == QtCore.QEvent.KeyPress: if event.key() == QtCore.Qt.Key_Tab: self.do_something() return super(Dialog, self).eventFilter(obj, event) <ul><li>Using activated signal of QShorcut:</li> </ul><hr />class Dialog(QtWidgets.QDialog, UI): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setupUi(self) self.button.clicked.connect(self.do_something) shortcut = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Tab), self) shortcut.activated.connect(self.do_something) @QtCore.pyqtSlot() def do_something(self): print("do_something")

From the previous methods I prefer the latter because you do not need to overwrite anything and you can connect to several functions.

On the other hand, only events are detected when the focus is in the Qt window.

Answer2:

I assume you put your widget in QDialog widget, so if you want to implement your own key press event, you should override the <strong>keyPressEvent</strong> of your Dialog widget, then it can behave as you like.

Here's an example,

from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QDialog class UI(QDialog): def __init__(self): super(UI, self).__init__() # ... self.button.clicked.connect(self.do_something) def do_something(self): # Something here def keyPressEvent(self, event): # when press key is Tab call your function if event.key() == Qt.Key_Tab: self.do_something()

Recommend

  • How to convert array of words to make a sentence?
  • Displaying Hindi font in jsp
  • Mongodb : Why convert string date to ISOdate if comparison operators work?
  • Facebook popup remember when user likes
  • How to overlay another div on the video?
  • Python SKLearn: How to Get Feature Names After OneHotEncoder?
  • SherlockActivity cannot be resolved to a type in android
  • Creating a custom control in Xamarin
  • Intent-Filter within a Service
  • Bounding csv data to topojson path - cloropleth
  • File structure for PHP-based website
  • Installation failed for laravel/lumen-installer: guzzlehttp/guzzle locked at 6.3.0
  • Hibernate Idempotent Update
  • Azure NodeJS Error: ENOENT, open 'D:\\home\\site\\wwwroot\\bin\\views\\'
  • Signed Java web start application with Glassfish 4.1 and Java7
  • Fortran function variable length string return
  • Does hibernate load two seprate copies of same instance if they are loaded twice from database?
  • Autocomplete source from project settings
  • 'Edit' function for forum posts and such
  • Wireshark Display Filter for Unique Source/Destination IP and Protocol
  • How to create subsets of a single set of elements with XSLT?
  • How convert html to BBcode in C#
  • Is there a better way for handling SpatialPolygons that cross the antimeridian (date line)?
  • How to call jQuery function in HTML returned by AJAX
  • Terminal run dalvikvm with am.jar
  • How to specify generic type when the type is only known at runtime?
  • Android: Unable to detect vertical plane
  • How do I add a mouse over tooltip to an Image using .DrawImage()
  • How to integrate angular2-material (alpha 8.2) with angular2-Quickstart app
  • How to warp text around image in iOS?
  • How to handle div that is created dynamically in a table
  • Google App Engine backend servlet not responding
  • What is the best way to cache and reuse immutable singleton objects in Java?
  • Make checkout phone field optional for specific countries in WooCommerce
  • Excel VBA : conditional formatting of sheet1 cells from sheet2 values in excel 2007
  • Codeigniniter insert data through models and controller
  • Android Library Projects on Windows and Mac
  • ReferenceError: TextEncoder is not defined