PyQt5 series of tutorials (29) keyboard events

Software and hardware environment

  • Windows 10 64bit
  • Anaconda3 with python 3.8
  • PyQt5 5.15

foreword

In the previous section, we introduced mouse events. In this section, we introduce keyboard events, which are also an important means of GUI operations, such as the common F1 key to display help, ctrl+c to copy, and ctrl+v to paste.

keyboard press up

The events corresponding to the pressing and pop-up of the keyboard keys are keyPressEvent and keyReleaseEvent . If you need to perform corresponding logic processing after the event occurs, you only need to rewrite these two methods in the window.

 def keyPressEvent(self, event): # 判断按下的是什么键if event.key() == Qt.Key_D: print('keyPressEvent, Key_D') # ctrl 修饰键if event.modifiers() & Qt.ControlModifier: print('Ctrl+D') # alt 修饰键elif event.modifiers() & Qt.AltModifier: print('Alt+D') # shift 修饰键elif event.modifiers() & Qt.ShiftModifier: print('Shift+D') def keyReleaseEvent(self, event): print('keyReleaseEvent')

Shortcut settings

Here, we set a shortcut key for the button in the interface, and the corresponding operation is to click

 self.pushButton.clicked.connect(self.onClick) # 给按钮操作设置一个快捷键A self.pushButton.setShortcut(QKeySequence(Qt.Key_A)) # 或者这样# self.shortcut_button = QShortcut(QKeySequence('Ctrl+S'), self) # self.shortcut_button.activated.connect(self.onClick)

In this way, when the focus is within the scope of the interface, pressing the letter A key is equivalent to clicking the button on the interface

Source code download

https://github.com/xugaoxiang/learningPyQt5

PyQt5 series of tutorials

For more PyQt5 tutorials, please move

https://xugaoxiang.com/category/python/pyqt5/

This article is reprinted from https://xugaoxiang.com/2022/05/31/pyqt5-29-keyboard-event/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment