Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a notification/event/signal when a Qt widget gets focus

Tags:

focus

qt

You can add en event filter.
This is an example of an application written with QtCreator. This form has a QComboBox named combobox.


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->comboBox->installEventFilter(this);
    .
    .
    .
}

bool MainWindow::eventFilter(QObject *object, QEvent *event)
{
    if (event->type() == QEvent::FocusOut)
    {
        if (object == ui->comboBox)
        {
            qWarning(object->objectName().toLatin1().data());
        }
    }
    return false;
}

There is a "focusChanged" signal sent when the focus changes, introduced in Qt 4.1.
It has two arguments, he widget losing focus and the one gaining focus:

void QApplication::focusChanged(QWidget * old, QWidget * now)

Qt Designer isn't designed for this level of WYSIWYG programming.

Do it in C++:

class LineEdit : public QLineEdit
{
    virtual void focusInEvent( QFocusEvent* )
    {}
};

The simplest way is to connect a slot to the QApplication::focusChanged signal.


I'd have to play with it, but just looking at the QT Documentation, there is a "focusInEvent". This is an event handler.

Here's how you find information about.... Open up "QT Assistant". Go to the Index. Put in a "QLineEdit". There is a really useful link called "List of all members, including inherited members" on all the Widget pages. This list is great, because it even has the inherited stuff.

I did a quick search for "Focus" and found all the stuff related to focus for this Widget.


You have hit on of the weird splits in QT, if you look at the documentation focusInEvent is not a slot it is a protected function, you can override it if you are implementing a subclass of your widget. If you you just want to catch the event coming into your widget you can use QObject::installEventFilter it let's you catch any kind of events.

For some odd reason the developers of Trolltech decided to propagate UI events via two avenues, signals/slots and QEvent


Just in case anybody looking for two QMainWindow focus change . You can use

if(e->type() == QEvent::WindowActivate)
{
    //qDebug() << "Focus IN " << obj << e ;

}