开发者

Preventing keyboard shortcuts being triggered in QScintilla (example code)

开发者 https://www.devze.com 2023-04-11 21:28 出处:网络
I would like t开发者_C百科o prevent application keyboard shortcuts from being triggered when editing code in my QScintilla widget, just like a normal QLineEdit field doesn\'t.

I would like t开发者_C百科o prevent application keyboard shortcuts from being triggered when editing code in my QScintilla widget, just like a normal QLineEdit field doesn't.

In the executable example code below it is not possible to type whitespaces in the QScintilla widget because the spacebar has been set as a shortcut, but in the QLineEdit it works properly.

I wonder if it could be something to do with the QScintilla not grabbing keyboard input properly (though it obviously does, since it is possible to input characters in it).

import sys,os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import Qsci

class MyWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.butt = QPushButton("button!!")       
        self.act = QAction("new act",self)
        self.act.setShortcut(QKeySequence(Qt.Key_Space))
        self.act.triggered.connect(tjosan)
        self.butt.clicked.connect(self.act.trigger)
        self.sci = Qsci.QsciScintilla()
        vbox = QVBoxLayout()    
        vbox.addWidget(self.sci)
        vbox.addWidget(QLineEdit())
        vbox.addWidget(self.butt)
        self.setLayout(vbox)
        self.addAction(self.act)

def tjosan():
    print "action !!!"

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widg = MyWidget()
    widg.show()
    sys.exit(app.exec_())


You need to filter ShortcutOverride events to get the same behaviour as QLineEdit. Here's an edited version of your example that demonstrates a way to do that:

import sys,os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import Qsci

class MyWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.butt = QPushButton("button!!")
        self.act = QAction("new act",self)
        self.act.setShortcut(QKeySequence(Qt.Key_Space))
        self.act.triggered.connect(tjosan)
        self.butt.clicked.connect(self.act.trigger)
        self.sci = Qsci.QsciScintilla()
        self.sci.installEventFilter(self)
        vbox = QVBoxLayout()
        vbox.addWidget(self.sci)
        vbox.addWidget(QLineEdit())
        vbox.addWidget(self.butt)
        self.setLayout(vbox)
        self.addAction(self.act)

    def eventFilter(self, widget, event):
        if (event.type() == QEvent.ShortcutOverride and
            widget is self.sci):
            print 'ShortcutOverride'
            event.accept()
            return True
        return QWidget.eventFilter(self, widget, event)

def tjosan():
    print "action !!!"

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widg = MyWidget()
    widg.show()
    sys.exit(app.exec_())
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号