# p03/ch09 — Qt 示例

## 可运行示例

| 目标 | 源文件 | 说明 |
|---|---|---|
| `mouse_event` | `mouse_event.cpp` | 构建运行见顶层 README；离屏验证 `QT_QPA_PLATFORM=offscreen tools/run_qt.sh mouse_event` |
| `event_override_customwidget` | `event_override_customwidget.cpp` | 构建运行见顶层 README；离屏验证 `QT_QPA_PLATFORM=offscreen tools/run_qt.sh event_override_customwidget` |
| `event_filter_mainwindow` | `event_filter_mainwindow.cpp` | 构建运行见顶层 README；离屏验证 `QT_QPA_PLATFORM=offscreen tools/run_qt.sh event_filter_mainwindow` |

## 参考片段（签名/伪代码，未单独建目标）

### [block 1] .1 事件

```cpp
label->setMouseTracking(true);
```

### [block 3] .2 event（）

```cpp
bool CustomTextEdit::event(QEvent *e)
{
if (e->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e);
if (keyEvent->key() == Qt::Key_Tab)
{
qDebug() << "You press tab.";
return true;
}
}
return false;
}
```

### [block 4] .2 event（）

```cpp
switch (event->type()) {
case QEvent::MouseMove:
mouseMoveEvent((QMouseEvent*)event);
break;
// ...
}
```

### [block 5] .2 event（）

```cpp
//!!! Qt5
bool QObject::event(QEvent *e)
{
switch (e->type()) {
case QEvent::Timer:
timerEvent((QTimerEvent*)e);
break;
case QEvent::ChildAdded:
case QEvent::ChildPolished:
case QEvent::ChildRemoved:
childEvent((QChildEvent*)e);
break;
// ...
default:
if (e->type() >= QEvent::User) {
customEvent(e);
break;
}
return false;
}
return true;
}
```

### [block 7] .3 事件过滤器

```cpp
bool CustomWidget::event(QEvent *e)
{
if (e->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e);
if (keyEvent->key() == Qt::Key_Tab) {
qDebug() << "You press tab.";
return true;
}
}
return QWidget::event(e);
}
现在，我们可以给出一个使用事件过滤器的版本：
bool FilterObject::eventFilter(QObject *object, QEvent *event)
{
if (object == target && event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Tab) {
qDebug() << "You press tab.";
return true;
} else {
return false;
}
}
return false;
}
```

### [block 8] .4 总结

```cpp
LRESULT CALLBACK WndProc(HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
```

### [block 9] .4 总结

```cpp
switch(message)
{
case WM_PAINT:
// ...
break;
case WM_DESTROY:
// ...
break;
...
}
```

### [block 10] .4 总结

```cpp
virtual bool QCoreApplication::notify ( QObject * receiver,
QEvent * event );
```

