Qt Creator鼠标事件与滚轮事件

鼠标事件:使用QMouseEvent类获取鼠标事件信息,在窗口部件中按下、移动鼠标都会产生鼠标事件。可以重定义鼠标事件的处理函数使得其能够完成你想完成的自定义事件。

滚轮事件:使用QWheelEvent类获取滚轮移动方向和距离,

如下例子:

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);//滚轮事件
 
 
};

    接下来是具体实现:

{
    ui->setupUi(this);
    QCursor cursor;                      // 创建光标对象
    cursor.setShape(Qt::OpenHandCursor); // 设置光标形状
    setCursor(cursor);                   // 使用光标
}
 
 
void Widget::mousePressEvent(QMouseEvent *event) // 鼠标按下事件
{
    if(event->button() == Qt::LeftButton){       // 如果是鼠标左键按下
        QCursor cursor;
        cursor.setShape(Qt::ClosedHandCursor);
        QApplication::setOverrideCursor(cursor); // 使鼠标指针暂时改变形状
        offset = event->globalPos() - pos();    // 获取指针位置和窗口位置的差值,这个globalPos()获取的是鼠标在桌面上的位置,
也可以使用pos()函数获取指针在窗口的位置。
    }
    else if(event->button() == Qt::RightButton){ // 如果是鼠标右键按下
        QCursor cursor(QPixmap("...logo.png"));//获取图片路径
        QApplication::setOverrideCursor(cursor);// 使用自定义的图片作为鼠标指针
    }
}
 
 
void Widget::mouseMoveEvent(QMouseEvent *event) // 鼠标移动事件
{
    if(event->buttons() & Qt::LeftButton){      // 这里必须使用buttons(),因为鼠标移动过程中会检测所有按下的键,而这个时候
button()是无法检测那个按键被按下,所以必须使用buttons()函数,看清楚,是buttons()不是button()
        QPoint temp;
        temp = event->globalPos() - offset;
        move(temp);// 使用鼠标指针当前的位置减去差值,就得到了窗口应该移动的位置
    }
}
 
 
void Widget::mouseReleaseEvent(QMouseEvent *event) // 鼠标释放事件
{
    Q_UNUSED(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)    // 滚轮事件,滚轮默认滚动一下是15度,此时date()函数会返回15*8=120的整数
,当滚轮远离返回正值,反之负值。
{
    if(event->delta() > 0){                    // 当滚轮远离使用者时
        ui->textEdit->zoomIn();                // 进行放大
    }else{                                     // 当滚轮向使用者方向旋转时
        ui->textEdit->zoomOut();               // 进行缩小
    }
}

猜你喜欢

转载自blog.csdn.net/smarterr/article/details/80781368