pythonpyqt4signalspyqt5spacebars

Key Press Connect at Start of Execution


I have a Python 3.6.3 script that incorporates PyQt5. The GUI has a button that toggles play and pause of a video file. Pressing the spacebar also toggles play and pause. The button works fine all the time. The spacebar also works as intended, except at the very start of executing the script. I need to click some other event first (such as a button or slider bar) before the spacebar will correctly triggers the signal to pause or play the video. I want to start playing the video with the spacebar when the script starts up. Here is how I create the connections in the same __init__(self) function . As you can see, clicking on the button and pressing the spacebar both connect the signal to the same function (self.pauseVideo).

self.btnPause = QtWidgets.QPushButton(self.centralwidget)
self.btnPause.clicked.connect(self.pauseVideo)

self.spacebar = QShortcut(QKeySequence(Qt.Key_Space), self)
self.spacebar.activated.connect(self.pauseVideo)

Suggestions on how to get the spacebar to trigger the signal when the script first starts?


Solution

  • After a lot more searching, reassigning keyboard shortcuts (without success), etc., I found this post PyQt widget keyboard focus. I inserted

    self.setFocusPolicy(Qt.StrongFocus)

    into __init__(self) and it seemed to solve my problem! Now I'm just hoping it doesn't cause other issues.