以前在Linux下写过关于鼠标的应用程序,通过read系统调用去读取/dev/input/mice设备节点数据,然后做一些数据相关的处理,然后显示鼠标光标等,这里就牵扯到一些图片相关的算法了,比如图像的缩放,合并。自从开始学C++和QT后才发现以前真的是瞎折腾,什么自己造*。QT类已经帮你做好这一切了,只需要去调用类就行。
QT中关于鼠标的类是QMouseEvent,我们在设计界面上添加一个Text Edit。用来作为输入。鼠标中常用的事件有:
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void mouseDoubleClickEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void wheelEvent(QWheelEvent *event);
这些函数只看函数名大家也应该知道其作用是什么了,下面是我的代码:代码相对比较简单,我就不做过多的介绍了,代码的作用是方便读者怎么去使用鼠标类的接口,可以当做是笔记吧。
main.cpp
#include <QtGui/QApplication>#include "widget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
widget.h
#ifndef WIDGET_H#define WIDGET_H#include <QWidget>#include <QMouseEvent>namespace Ui {class Widget;}class Widget : public QWidget{ Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private: Ui::Widget *ui; QPoint offset;protected: void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void mouseDoubleClickEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void wheelEvent(QWheelEvent *event);};#endif // WIDGET_H
widget.cpp
#include "widget.h"#include "ui_widget.h"Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget){ ui->setupUi(this); QCursor cursor; cursor.setShape(Qt::OpenHandCursor); setCursor(cursor);}Widget::~Widget(){ delete ui;}void Widget::mousePressEvent(QMouseEvent *event){ if(event->button() == Qt::LeftButton){ QCursor cursor; cursor.setShape(Qt::ClosedHandCursor); QApplication::setOverrideCursor(cursor); offset = event->globalPos() - pos(); } else if(event->button() == Qt::RightButton) { QCursor cursor(QPixmap("../mouse.png")); QApplication::setOverrideCursor(cursor); }}void Widget::mouseMoveEvent(QMouseEvent *event){ if(event->buttons() & Qt::LeftButton) { QPoint temp; temp = event->globalPos() - offset; move(temp); }}void Widget::mouseReleaseEvent(QMouseEvent *event){ QApplication::restoreOverrideCursor();}void Widget::mouseDoubleClickEvent(QMouseEvent *event){ if(event->button() == Qt::LeftButton) { if(windowState() != Qt::WindowFullScreen) setWindowState(Qt::WindowFullScreen); else setWindowState(Qt::WindowNoState); }}void Widget::wheelEvent(QWheelEvent *event){ if(event->delta() > 0){ ui->textEdit->zoomIn(); }else{ ui->textEdit->zoomOut(); }}