python - PyQt widget keyboard focus -


first off -- group! started delving pyqt month or ago. in time, i've bumped against many questions, , virtually found answer here.

until now.

i have workaround this, think it's kluge , there proper way. i'd understand better what's going on.

here's code:

from pyqt5.qtcore       import * pyqt5.qtgui        import * pyqt5.qtwidgets    import *   class formwidget(qwidget):     def __init__(self, parent):                 super(formwidget, self).__init__(parent)          # create view image in         self.image = qgraphicspixmapitem(qpixmap())         self.scene = qgraphicsscene()         self.scene.additem(self.image)         self.view = qgraphicsview(self.scene)          self.hlayout = qhboxlayout()         self.hlayout.addwidget(self.view)         self.setlayout(self.hlayout)  #       self.view.keypressevent = self.keypressevent      def keypressevent(self, event):         key = event.key()         mod = int(event.modifiers())         print(             "<{}> key 0x{:x}/{}/ {} {} {}".format(                 self,                 key,                 event.text(),                 "  [+shift]" if event.modifiers() & qt.shift else "",                 "  [+ctrl]" if event.modifiers() & qt.ctrl else "",                 "  [+alt]" if event.modifiers() & qt.alt else ""             )         )   class mainwindow(qmainwindow):      def __init__(self, parent=none):         super(mainwindow, self).__init__(parent)         form = formwidget(self)          self.setcentralwidget(form)    if __name__ == '__main__':     import sys     app = qapplication(sys.argv)     mainwindow = mainwindow()     mainwindow.show()     sys.exit(app.exec_()) 

as is, keyboard input detected overloaded keypressevent() function, except arrow keys. i've found enough posts talking have sense because child widget (self.view) receiving them. presume child widget is, in fact, receiving all keystrokes, ignoring ones getting through, , sucking arrow keys, why aren't getting parent's keypressevent() function. seems so, because if uncomment line in middle:

        self.view.keypressevent = self.keypressevent 

it behaves expect -- parent's keypressevent() gets keystrokes, arrows included.

how tell child widget ignore keystrokes? thought maybe this:

        self.view.setfocuspolicy(qt.nofocus) 

when add that, keypressevent() doesn't see any keystrokes @ all.

i suppose overload keypressevent() child well, , explicitly pass parent. doesn't seem better kluge.

i think must misunderstanding here.

thanks. looking learn ...

by default, qwidget not accept keyboard focus, need enable explicitly:

class formwidget(qwidget):     def __init__(self, parent):         ...          self.setfocuspolicy(qt.strongfocus) 

Comments