How to override functionality for widgets hiding when losing mouse focus?



  • I need some kind of way to replace the existing functionality where a widget will hide automatically when a click occurs outside of it ( loses focus) with my own code to do something else instead.


  • Moderators

    Hi, and welcome to the Qt forum.

    widget will hide automatically when [...] loses focus [...]

    You can override QWidget::focusOutEvent(QFocusEvent *event), see: focusOutEvent().

    class MyPlainTextEdit : public QPlainTextEdit
    {
        Q_OBJECT
    public:
        explicit MyPlainTextEdit(QWidget *parent = nullptr);
    protected:
        virtual void focusOutEvent(QFocusEvent *) override { hide(); }
    };
    


  • Thank you. The problem is that I need to implement this in the eventFilter of my QMainWindow to filter for the correct object. I cannot implement this function for the object I need since there's no class implementation for that object, it's all part of my QMainWindow. How would I do this?


  • Moderators

    Let's assume you have your MainWindow class and it contains the widget plainTextEdit.

    myeventfilter.h

    #ifndef MYEVENTFILTER_H
    #define MYEVENTFILTER_H
    
    #include <QObject>
    
    class MyEventFilter : public QObject
    {
        Q_OBJECT
    public:
        MyEventFilter(QObject *parent = nullptr);
    protected:
        virtual bool eventFilter(QObject *watched, QEvent *event) override;
    };
    
    #endif // MYEVENTFILTER_H
    

    myeventfilter.cpp

    #include "myeventfilter.h"
    #include <QEvent>
    #include <QWidget>
    
    MyEventFilter::MyEventFilter(QObject *parent)
        : QObject(parent)
    {
    }
    
    bool MyEventFilter::eventFilter(QObject *watched, QEvent *event)
    {
        if (event->type() == QEvent::FocusOut) {
            auto widget = dynamic_cast<QWidget *>(watched);
            widget->hide();
            return true;
        } else {
            return QObject::eventFilter(watched, event);
        }
    }
    

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include "myeventfilter.h"
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        auto myEventFilter = new MyEventFilter(this);
        ui->plainTextEdit->installEventFilter(myEventFilter);
    }
    
    // ...
    


  • @Qtstarter121 ,

    Hi,

    You can use,
    yourWidget->setWindowFlags(Qt::Popup);
    this will hide your widget when you click outside of it.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.