使用installEventFilter过滤mousePressEvent

joj*_*ojo 3 python qt

我有问题,过滤"mousePressEvent"installEventFilter

MyTestxEdit是一个小部件,QTextEdit 我希望所有的事件都QTextEdit将被处理MyTestxEdit 我已经使用了installEventFilter 这个伎俩适用于事件,keyPressEvent但不处理mousePressEvent 我做错了什么?

import sys
from PyQt4.QtGui import QApplication, QErrorMessage
from KdeQt.KQApplication import KQApplication
from KdeQt.KQMainWindow import KQMainWindow
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import thread

class MyTestxEdit1(QTextEdit):
    def __init__(self,parent):
        QTextEdit.__init__(self)
        self.setMouseTracking(True)

class MyTestxEdit(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.__qTextEdit=MyTestxEdit1(self)
        self.__qHBoxLayout=QHBoxLayout()
        self.setLayout(self.__qHBoxLayout)
        self.__qHBoxLayout.addWidget(self.__qTextEdit)        
        self.__qTextEdit.installEventFilter(self)


    def eventFilter(self,target,event):
        print "eventFilter "+str(event.type())
        if(event.type()==QEvent.MouseButtonPress):
            print "Mouse was presssed "+str(event.type())
            self.mousePressEvent(event) 
            return True
        return False                   


if __name__ == '__main__':
    app = KQApplication(sys.argv,[])
    mainWindow = KQMainWindow()#loc, splash, pluginFile, noopen, restartArgs)
    s = QSize(800, 600)
    mainWindow.resize(s)    
    testxEdit=MyTestxEdit()
    mainWindow.setCentralWidget(testxEdit)

    mainWindow.show()
    res = app.exec_()
    sys.exit(res)    
Run Code Online (Sandbox Code Playgroud)

And*_*y M 6

尝试在QTextEdit's视口而不是QTextEdit自身上安装过滤器...

我不知道python,但是像:

self.__qTextEdit.viewport().installEventFilter(self)
Run Code Online (Sandbox Code Playgroud)

我希望它有所帮助!

你应该做的事情如下:

MyClassFrm::MyClassFrm()
{
    ...
    // Get your TextEdit from the UI here , or create your TextEdit here....
    // Install the filter
    pMyTextEdit->viewport()->installEventFilter(this);
    ...
}

...

bool MyClassFrm::eventFilter(QObject* pObject, QEvent* pEvent)
{
    if (pEvent->type() == QEvent::MousePressEvent) 
    {
        qDebug() << "Mouse pressed !!";
        // standard event processing
        return QObject::eventFilter(pObject, pEvent);
    }
}
Run Code Online (Sandbox Code Playgroud)

你应该能够使它工作,我只是在我的应用程序中测试,它的工作原理......我相信你很接近!