Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

eventFilter run many times



  • https://github.com/sonichy/HTYFileManager
    I am writing a file manager, and I want to capture enter to open file.
    The lineEditLocation, listView and tableView will emit enter press event.
    Use eventFilter, every object run 3 times !
    When I open a image file in QListView, it will open 3 windows of the image.

    lineEditLocation->installEventFilter(this);
    ui->listView->installEventFilter(this);
    ui->tableView->installEventFilter(this);
    
    bool MainWindow::eventFilter(QObject *obj, QEvent *event)
    {
        QKeyEvent *KE = static_cast<QKeyEvent*>(event);
        if (KE->key() == Qt::Key_Return || KE->key() == Qt::Key_Enter) {
            qDebug() << "eventFilter" << obj;
            if (obj == lineEditLocation) {
                openL();
            } else if (obj == ui->listView) {
                if(ui->listView->selectionModel()->selectedIndexes().size() != 0)
                    open(ui->listView->selectionModel()->selectedIndexes().at(0));            
            } else if (obj == ui->tableView) {
                if(ui->tableView->selectionModel()->selectedIndexes().size() != 0)
                    open(ui->tableView->selectionModel()->selectedIndexes().at(0));            
            }
        }
        return QObject::eventFilter(obj, event);
    }
    


  • Hello,

    You have to return true when the event has been "consumed". I think the event is propagated three times as you have installed three event filters and you don't stop event propagation.

    lineEditLocation->installEventFilter(this);
    ui->listView->installEventFilter(this);
    ui->tableView->installEventFilter(this);
    
    bool MainWindow::eventFilter(QObject *obj, QEvent *event)
    {
        QKeyEvent *KE = static_cast<QKeyEvent*>(event);
        if (KE->key() == Qt::Key_Return || KE->key() == Qt::Key_Enter) {
            qDebug() << "eventFilter" << obj;
            if (obj == lineEditLocation) {
                openL();
            } else if (obj == ui->listView) {
                if(ui->listView->selectionModel()->selectedIndexes().size() != 0)
                    open(ui->listView->selectionModel()->selectedIndexes().at(0));            
            } else if (obj == ui->tableView) {
                if(ui->tableView->selectionModel()->selectedIndexes().size() != 0)
                    open(ui->tableView->selectionModel()->selectedIndexes().at(0));            
            } else return QObject::eventFilter(obj, event);
            return true;  //return TRUE, stopping event propagation
        }
        return QObject::eventFilter(obj, event);
    }
    

    This could be the issue.
    From the doc: "The eventFilter() function must return true if the event should be filtered, (i.e. stopped); otherwise it must return false."



  • @Gojir4 Thank you !


Log in to reply