Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyqtgraph: where to find signal for key preses?

The following example shows how to connect an arbitrary python callable to mouse motion events in a GraphicsWindow. How would you do the same for key press events?

from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg

app = pg.mkQApp()
win = pg.GraphicsWindow()
pl = win.addPlot()
pl.plot([x*x for x in range(-10,11)])

def mouseMoved(evt):
    print("Mouse moved event: {}".format(evt))

pl.scene().sigMouseMoved.connect(mouseMoved)

def keyPressed(evt):
    print("Key pressed")

# The scene doesn't have an equivalent signal for key presses
# pl.scene().sigKeyPressed.connect(keyPress)

app.exec_()
like image 950
jacg Avatar asked Nov 04 '16 13:11

jacg


2 Answers

Even though, it has been quite a while since this question has been asked, I still hope that my answer helps.

The solution is to derive a class from pyqtgraph.GraphicsWindow and then define a keypress signal.

from pyqtgraph.Qt import QtCore
import pyqtgraph as pg

class KeyPressWindow(pg.GraphicsWindow):
    sigKeyPress = QtCore.pyqtSignal(object)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def keyPressEvent(self, ev):
        self.scene().keyPressEvent(ev)
        self.sigKeyPress.emit(ev)


def keyPressed(evt):
    print("Key pressed")


app = pg.mkQApp()
win = KeyPressWindow()
win.sigKeyPress.connect(keyPressed)
pl = win.addPlot()
pl.plot([x*x for x in range(-10,11)])


app.exec_()
like image 61
user1513370 Avatar answered Nov 17 '22 12:11

user1513370


Small update/enhancement to @user1513370's answer.

I've replaced deprecated pg.GraphicsWindow with pg.GraphicsLayoutWidget, removed the redundant call to __init__ and added mapping from keycodes defined in the Qt namespace to key names.

from pyqtgraph.Qt import QtCore
import pyqtgraph as pg
from collections import defaultdict

# Get key mappings from Qt namespace
qt_keys = (
    (getattr(QtCore.Qt, attr), attr[4:])
    for attr in dir(QtCore.Qt)
    if attr.startswith("Key_")
)
keys_mapping = defaultdict(lambda: "unknown", qt_keys)

class KeyPressWindow(pg.GraphicsLayoutWidget):
    sigKeyPress = QtCore.pyqtSignal(object)

    def keyPressEvent(self, ev):
        self.scene().keyPressEvent(ev)
        self.sigKeyPress.emit(ev)


app = pg.mkQApp()
win = KeyPressWindow(show=True)
win.sigKeyPress.connect(lambda event: print(keys_mapping[event.key()]))
win.addPlot().plot([x*x for x in range(-10,11)])

app.exec()
like image 1
MarcinKonowalczyk Avatar answered Nov 17 '22 11:11

MarcinKonowalczyk