当前位置:网站首页>QT event filter simple case

QT event filter simple case

2022-07-05 09:55:00 Sunqk5665

1、 Create a new one widget,ui The interface design is as follows

 Insert picture description here

2、widget.h Add constructor to

 Insert picture description here

bool eventFilter(QObject *watched, QEvent *event);

3、 stay widget.cpp Add the following code to

Add header file
 Insert picture description here

#include <QKeyEvent>
#include <QWheelEvent>

Install the filter :
 Insert picture description here

ui->textEdit->installEventFilter(this);
ui->spinBox->installEventFilter(this);
ui->label->installEventFilter(this);

Add filter refactoring function :

bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    
    if(watched==ui->textEdit)
    {
    
        if(event->type()==QEvent::Wheel)
        {
    
            QWheelEvent *wheelEvent = (QWheelEvent*)event;
            if(wheelEvent->delta()>0)
                ui->textEdit->zoomIn();
            else
                ui->textEdit->zoomOut();
        }
    }
    else if(watched==ui->spinBox)
    {
    
        if(event->type()==QEvent::KeyPress)
        {
    
            QKeyEvent *keyEvent = (QKeyEvent*)event;
            if(keyEvent->key()==Qt::Key_Space)
                ui->spinBox->setValue(0);
        }
    }
    else if(watched==ui->label)
    {
    
        if(event->type()==QEvent::MouseButtonPress)
        {
    
            QMouseEvent *mouseEvent = (QMouseEvent*)event;
            if(mouseEvent->button()==Qt::LeftButton)
                ui->textEdit->setText(tr(" Left click on the picture !"));
            else if(mouseEvent->button()==Qt::RightButton)
                ui->textEdit->setText(tr(" Right click on the picture !"));
        }
    }
    else
        return QWidget::eventFilter(watched,event);
    return false;
}

4、 Run the project

Click the picture with the left mouse button
 Insert picture description here
Right click on the picture
 Insert picture description here
Mouse in textEdit Slide the roller up , Changed the font size
 Insert picture description here

原网站

版权声明
本文为[Sunqk5665]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140535206490.html