使用installEventFilter过滤mousePressEvent

3 投票
1 回答
3792 浏览
提问于 2025-04-15 16:18

我在用 installEventFilter 过滤 "mousePressEvent" 的时候遇到了问题。

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)    

1 个回答

6

试着把过滤器安装在 QTextEdit 的视口上,而不是直接在 QTextEdit 本身上...

我不太懂python,但大概可以这样做:

self.__qTextEdit.viewport().installEventFilter(self)

希望这能帮到你!

你应该这样做:

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);
    }
}

你应该能让它工作,我刚在我的应用程序里测试过,确实有效... 我相信你快成功了!

撰写回答