简体   繁体   中英

Pipe all keyboard commands automatically to an embedded mplayer instance when a modifier key is pressed in pyqt4

This is a follow up question to this answer: https://stackoverflow.com/a/11939294/406686 :

Consider the following code, which embeds mplayer in a QWidget . The problem is that it doesn't react to any mplayer keyboard shortcuts such as right arrow for seek forward and so on.

It's clear that I can reimplement every shortcut manually. However is there a way to pipe all keyboard sequences automatically to mplayer as long as a modifier key, say ALT or Win-Key is pressed?

For example: Press ALT + = seek forward...

import mpylayer
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.container = QtGui.QWidget(self)
        self.container.setStyleSheet('background: black')
        self.button = QtGui.QPushButton('Open', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.container)
        layout.addWidget(self.button)
        self.mplayer = mpylayer.MPlayerControl(
            'mplayer', ['-wid', str(self.container.winId())])

    def handleButton(self):
        path = QtGui.QFileDialog.getOpenFileName()
        if not path.isEmpty():
            self.mplayer.loadfile(unicode(path))

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

I am not sure, if I got your problem right. You could easily add the keyPressEvent and keyReleaseEvent methods to your Window Class:

class Window(QtGui.QWidget):
    def __init__(self):
        # same code as above
        self.setFocus()
        self.__modifier_pressed = False

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Alt:
            self.__modifier_pressed = True
        elif self.__modifier_pressed:
            self.mplayer.run_command("key_down_event", event.nativeVirtualKey())

    def keyReleaseEvent(self, event):
        if event.key() == QtCore.Qt.Key_Alt:
            self.__modifier_pressed = False

This example would only work with Modifier+ONE other key. If you also need this for more complex shortcuts, such as Alt + Ctrl + Shift + , you might need lists to save the currently pressed keys, but the basic idea should be clear.

On my computer, the pressed key of python and the received one from mplayer are different, but I use a very uncommon keyboard layout ( Neo-Layout ), so this might be the reason for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM