Luc PHAN
Luc PHAN

Reputation: 310

QAction keyBindings

On Windows, there are several key bindings for standard actions. For example, to copy, one can use Ctrl+C or Ctrl+Insert.

How to handle that with Qt ? This is what I did:

  1. I got the list of key bindings with QKeySequence.keyBindings().
  2. I created 2 actions, one for Ctrl+C, another for Ctrl+Insert.

It seems to work.

Question: Is it the right way to handle key bindings with Qt ?

Full source code:

from sys import argv, exit
from PyQt4.QtGui import QApplication, QWidget, QAction, QKeySequence


class Widget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        for key in QKeySequence.keyBindings(QKeySequence.Copy):
            action = QAction("Copy", self)
            action.triggered.connect(self._copy)
            action.setShortcut(key)
            self.addAction(action)

    def _copy(self):
        print("Copy!")

print("On Windows, use Ctrl+C or Ctrl+Insert to copy.")
app = QApplication(argv)
w = Widget()
w.show()
exit(app.exec_())

Upvotes: 1

Views: 1192

Answers (1)

jonspaceharper
jonspaceharper

Reputation: 4367

You only need one action and a call to QAction::setShortcuts().

action = QAction("Copy", self)
action.setShortcuts(QKeySequence.keyBindings(QKeySequence.Copy))
action.triggered.connect(self._copy)

Upvotes: 4

Related Questions