Issue
I have one pushButton on my app, I want to trigger it when I press 'Return' or 'Enter'(num-pad) keyboard. I tried many way, but failed..
self.ui.PushButton1.setShortcut('return')
# I want like: (['return', 'enter'])
Solution
You can't use setShortcut()
if you want multiple shortcuts for the same button. Calling it the second time will clear the first shortcut.
You have to use multiple QShortCut
and connect their activated
signal.
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
from PyQt6.QtGui import QShortcut
class Window(QWidget):
def __init__(self):
super().__init__()
pb = QPushButton('push')
pb.clicked.connect(lambda: print('clicked'))
short1 = QShortcut('return', self)
short1.activated.connect(pb.click)
short2 = QShortcut('backspace', self)
short2.activated.connect(pb.click)
lay = QVBoxLayout(self)
lay.addWidget(pb)
app = QApplication([])
window = Window()
window.show()
app.exec()
Notes:
I used 'backspace' as a second key because I don't have numpad 'enter' on my keyboard.
On PyQt5, you have to import QShortcut
from QtWidgets
Since you connect both shortcuts to the same slot, you can shorten the code like this:
for key in ('return', 'backspace'):
QShortcut(key, self).activated.connect(pb.click)
Answered By - mahkitah
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.