对于在嵌入式或其它Qt项目中,事件是经常用的东西,很是方便.下面总结一些常用的例子,在例子中学习这个事件,会更快些.
一.实现移动鼠标获取坐标
#include <QApplication> #include <QWidget> #include <QLabel> #include <QMouseEvent> class EventLabel : public QLabel { protected: void mouseMoveEvent(QMouseEvent *event); //声明明三个事件函数 void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); }; void EventLabel::mouseMoveEvent(QMouseEvent *event) //鼠标移动事件函数,显示出鼠标的坐标 { this->setText(QString("<center><h1>Move: (%1, %2)</h1></center>") .arg(QString::number(event->x()), QString::number(event->y()))); } void EventLabel::mousePressEvent(QMouseEvent *event) //按下时,获得鼠标坐标 { this->setText(QString("<center><h1>Press: (%1, %2)</h1></center>") .arg(QString::number(event->x()), QString::number(event->y()))); } void EventLabel::mouseReleaseEvent(QMouseEvent *event) //松开鼠标时,获取鼠标的坐标 { QString msg; msg.sprintf("<center><h1>Release: (%d, %d)</h1></center>", event->x(), event->y()); this->setText(msg); } int main(int argc, char *argv[]) { QApplication app(argc, argv); EventLabel *label = new EventLabel; label->setWindowTitle("MouseEvent Demo"); label->resize(300, 200); label->show(); return app.exec(); }
一个小例子,就说明了鼠标事件的用法,调试这个小例子,很快就学会了.
时间: 2024-12-29 11:50:21