// ============================================================================ // mouse_event — Qt 桌面示例 // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 原文片段:[58954546:0] // 说明:本文件由 gen_part3.py 从 wiki 片段生成(必要时补 main/QApplication // 外壳、include、修正笔误)。详见 docs/ERRATA.md。 // 离屏验证:QT_QPA_PLATFORM=offscreen tools/run_qt.sh // ============================================================================ #include #include #include #include #include #include // 自定义 QLabel:重写鼠标事件,显示坐标 class EventLabel : public QLabel { Q_OBJECT public: explicit EventLabel(QWidget* p = nullptr) : QLabel(p) { setMouseTracking(true); // 启用鼠标移动追踪(默认只在按键时追踪) setText(QStringLiteral("移动鼠标到这里")); } protected: void mouseMoveEvent(QMouseEvent* event) override { setText(QString("

Move: (%1, %2)

") .arg(event->x()).arg(event->y())); } void mousePressEvent(QMouseEvent* event) override { setText(QString("

Press: (%1, %2)

") .arg(event->x()).arg(event->y())); } void mouseReleaseEvent(QMouseEvent* event) override { setText(QString("

Release: (%1, %2)

") .arg(event->x()).arg(event->y())); } }; int main(int argc, char* argv[]) { QApplication app(argc, argv); EventLabel w; w.show(); // 离屏/自动化验证:200ms 后自动退出(GUI 模式下不阻塞) QTimer::singleShot(200, &app, &QApplication::quit); return app.exec(); } #include "mouse_event.moc"