QT-Qtextedit mouse events

Overview

QT defines mouse events that can directly write mouse-related events in protected. However, it doesn't work in QTextedit.
For example:
under widget.h:

protected:
void mousePressEvent(QMouseEvent *event);        //单击
    void mouseReleaseEvent(QMouseEvent *event);      //释放
    void mouseDoubleClickEvent(QMouseEvent *event);  //双击
    void mouseMoveEvent(QMouseEvent *event);         //移动
    void wheelEvent(QWheelEvent *event);      

Then in
widget.cpp

void Widget::mousePressEvent(QMouseEvent *event)
{
    // 如果是鼠标左键按下   改变指针形状,并且存储当前指针位置与窗口位置的差值。
    if(event->button() == Qt::LeftButton){
        ···
    }
    // 如果是鼠标右键按下
    else if(event->button() == Qt::RightButton){
       ···
    }
}
......//以及剩下的操作

method

It can be processed in the way of time filter (this method is like opening, it is very versatile!): The
first is the header file:
widget.h

private slots:
    bool eventFilter(QObject *obj, QEvent *e);

Then:
widget.cpp

bool Widget::eventFilter(QObject* o, QEvent* e)
{
    Q_UNUSED(o);
    if(e->type() == QEvent::MouseButtonPress){
        QMouseEvent* pMe = static_cast<QMouseEvent*>(e);
        //这里不进行任何操作即代表使该手势失效
        qDebug() << pMe->pos();
        return true;
    }
    if(e->type()==QEvent::MouseButtonDblClick){
        QMouseEvent* pMe = static_cast<QMouseEvent*>(e);
        qDebug() << pMe->pos();
        //这里不进行任何操作即代表使该手势失效

        return true;
    }
    return false;
}

In addition, it needs to be registered when it is initialized:

this->myTextEdit->viewport()-> installEventFilter(this);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325755422&siteId=291194637