Qt/Utilities/EventFilter
From ProgrammingExamples
< Qt
main.cpp
#include <QProgressDialog> #include <QApplication> #include "form.h" int main( int argc, char **argv ) { QApplication app(argc, argv); MainWindow window; window.show(); return app.exec(); }
form.h
#ifndef FORM_H #define FORM_H #include "ui_main.h" #include <QTime> class MainWindow : public QMainWindow, public Ui::MainWindow { Q_OBJECT public: MainWindow(); bool eventFilter(QObject *object, QEvent *event); }; #endif
form.cpp
#include "form.h" // Qt #include <QtGui> #include <QEvent> // STL #include <iostream> MainWindow::MainWindow() { setupUi(this); lineEdit->installEventFilter(this); } bool MainWindow::eventFilter(QObject *object, QEvent *event) { if (object == lineEdit && event->type() == QEvent::FocusOut) { std::cout << "eventFilter" << std::endl; } return false; // Pass the event along (don't consume it) }
form.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>571</width>
<height>500</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>CMakeLists.txt
cmake_minimum_required(VERSION 2.6) PROJECT(EventFilter) FIND_PACKAGE(Qt4 REQUIRED) INCLUDE(${QT_USE_FILE}) QT4_WRAP_UI(UISrcs main.ui) QT4_WRAP_CPP(MOCSrcs form.h) include_directories(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) ADD_EXECUTABLE(EventFilter main.cpp form.cpp ${UISrcs} ${MOCSrcs}) TARGET_LINK_LIBRARIES(EventFilter ${QT_LIBRARIES})