Events in QT

catalogue

1. QT event

1.1 event introduction

1.2. Event handling

2. Keyboard events

2.1,keyPressEvent

2.1.1 judge whether a key is pressed

2.1.2 key combination operation

3. Mouse event

3.1. Mouse click event

3.2. Mouse release event

3.3. Double click event

3.4. Mouse movement events

3.5 roller events

4. Event filter

4.1. Use of event filter

5. Timer

5.1 implementation of QTimerEvent timer

5.2 implementation of QTimer timer

6. Random number seed

7. Drag event

Extension setting (right click menu bar):

1. QT event

1.1 event introduction

Event is a general term for events or actions that need to be known by various applications and generated internally or externally. In Qt, an object is used to represent an event, which inherits from QEvent class.

Common events: mouse event, keyboard event, timing event, context menu event, closing event, drag and drop event, drawing event.

1.2. Event handling

Overload related Event functions

Re implement event handling functions such as paintEvent(), mousePressEvent(). This is the most common method, but it can only be used to deal with specific events of specific parts. For example, this method is used to implement drag and drop operation.

Install event filter

Install the event filter on the object. Using event filter, you can handle different events of different subassemblies in one interface class at the same time.

2. Keyboard events

QKeyEvent

The QKeyEvent class is used to describe a keyboard event. When the keyboard key is pressed or released, the keyboard event is sent to the component with keyboard input focus.

In Qt assistant, find Qt::Key.

Example: Qt::Key_Escape means space, Qt::Key_Left ← key, etc

2.1,keyPressEvent

This can only be used if the header file is included. The following is taken from the original file

protected:    
    bool event(QEvent *event) Q_DECL_OVERRIDE;    
    virtual void mousePressEvent(QMouseEvent *event);//Mouse down
    virtual void mouseReleaseEvent(QMouseEvent *event);//Mouse release
    virtual void mouseDoubleClickEvent(QMouseEvent *event);//Double click the mouse
    virtual void mouseMoveEvent(QMouseEvent *event);//Mouse movement
#ifndef QT_NO_WHEELEVENT    
    virtual void wheelEvent(QWheelEvent *event); //Roller
#endif    
    virtual void keyPressEvent(QKeyEvent *event);//Press the key
    virtual void keyReleaseEvent(QKeyEvent *event);//Key release
    virtual void enterEvent(QEvent *event);//Enter
    virtual void leaveEvent(QEvent *event);//Leave
    virtual void paintEvent(QPaintEvent *event);//Draw
    virtual void moveEvent(QMoveEvent *event);//leave

Here, we will implement the virtual function defined and declared by the parent class

//Define it in your own class, and then implement it
protected:
virtual void keyPressEvent(QKeyEvent *event);//Press the key

2.1.1 judge whether a key is pressed

void Widget::keyPressEvent(QKeyEvent *event){    
    if(event->key()==Qt::Key_X)   {        
    qDebug()<<"X Press";   
    }
}

2.1.2 key combination operation

Search Qt::KeyboardModifier in Qt assistant as follows

void Widget::keyPressEvent(QKeyEvent *event){    
    if(event->modifiers()==Qt::ControlModifier)//Determine whether to press ctrl
    {        
        if(event->key()==Qt::Key_X)//Then judge whether it is x pressed
        {            
            qDebug()<<"ctrl+X";       
        }   
    }else if(event->key()==Qt::Key_X)   
    {        qDebug()<<"X Press";   
    }
}

3. Mouse event

QMouseEvent class is used to represent a mouse event. When the mouse is pressed or the mouse pointer is moved in the widget, a mouse event will be generated. Using QMouseEvent class, you can know which key of the mouse is pressed, and the current position of the mouse pointer. It is usually to redefine the mouse event handling function of the part to carry out some custom operations.  

The QWheelEvent class is used to represent the mouse wheel event. In this class, it is mainly used to obtain the moving direction and distance of the wheel. In the roller event processing function, the delta() function of QWheelEvent class is used to obtain the moving distance of the roller. Whenever the roller rotates, the default is 15 degrees. When the roller rotates away from the user, it returns a positive value; Returns a negative value when rotating in a direction close to the user. In this way, the return value of this function can be used to judge the moving direction of the roller.

3.1. Mouse click event

Qt::LeftButton  Left
Qt::RightButton right
Qt::MidButton   in
void Widget::mousePressEvent(QMouseEvent *event){    
    if(event->button()==Qt::LeftButton)   {        
    qDebug()<<"Left key press";   
    }
}

3.2. Mouse release event

void Widget::mouseReleaseEvent(QMouseEvent *event){    
    if(event->button()==Qt::LeftButton)   {        
        qDebug()<<"Left key release";   
    }
}

3.3. Double click event

void Widget::mouseDoubleClickEvent(QMouseEvent *event){    
    if(event->button()==Qt::LeftButton)   {        
        qDebug()<<"Double left click";   
    }
}

3.4. Mouse movement events

        setMouseTracking(true); This is false by default and needs to be set to true to obtain the mouse position in real time. Otherwise, it can be obtained only when you press it

void Widget::mouseMoveEvent(QMouseEvent *event)
{    
    qDebug()<<event->x()<<event->y();    
    qDebug()<<event->pos();//Coordinates relative to the window
    qDebug()<<event->globalPos();//Coordinates relative to the screen
}

3.5 roller events

void Widget::wheelEvent(QWheelEvent *event){    
    static int x=0;    
    x+=event->delta();//Or ± 120
    if(event->delta()>0)   
    {        
        qDebug()<<"Roller forward"<<x;   
    }else{        
        qDebug()<<"Roll back"<<x;   
    }
}

4. Event filter

There are events. What events are only handled on this control

For example: input any information in a dialog box, but it will not be input into it, but will be obtained

4.1. Use of event filter

//1. Install the filter
ui->textEdit->installEventFilter(this);
//2. Implement filter
//2.1. Declare function first
protected:
    virtual bool eventFilter(QObject *watched, QEvent *event);
//2.2. Rewrite function
bool Widget::eventFilter(QObject *watched, QEvent *event){
    if(watched == ui->textEdit){//2.2.1. Set the components you need to monitor
        if(event->type() == QEvent::KeyPress){//2.2.2. If it is a key pressed on the keyboard
            //Test effect
            QKeyEvent *keyen = static_cast<QKeyEvent*>(event);
            qDebug() << keyen->key();//Key value of output key
            return true;
        }else{
            return false;
        }
    }
    return Widget::eventFilter(watched,event);//This function needs to be monitored all the time, so here is a recursion
}

Effect display:

It is not difficult to see here that the component has captured the time when the key is pressed. This situation can refer to a login meeting. Copy and paste is prohibited, which is very similar, but the input method is not shielded. The same is true for other controls.

5. Timer

Timers are divided into two classes: QTimerEvent and QTimer

The QTimerEvent class is used to describe a timer event. For a subclass of QObject, you only need to use the int QObject:: starttimer (int interval) function to start a timer. This function needs to enter an integer in milliseconds as a parameter to indicate the set time, and it returns an integer number to represent the timer. When the timer overflows, you can get the number of the timer in the timerEvent() function for related operations.  

QTimer class is used to implement a timer. It provides a higher-level programming interface, such as using signals and slots, and setting a timer that runs only once.  

5.1 implementation of QTimerEvent timer

1,set timer 
private: 
    int id1;    
    int c;//It depends on the effect
2,Set time
    c = 1;
    id1=startTimer(c);//1 ms
3,Function implementation
protected:
    virtual void timerEvent(QTimerEvent *event);

void Widget::timerEvent(QTimerEvent *event){
    if(event->timerId() == id1){
        qDebug()<<id1;
        c+=1;
        id1 = startTimer(c);
    }
}
    

Effect display

5.2 implementation of QTimer timer

//1. Set timer
private:
    QTimer t1;    
    QTimer t2;

//2. Set time
    t1.start(1000);//1000 ms
    t2.start(2000);

/*3,Correlation signal and slot
    Slot function refers to the function to be executed at this time
*/
private slots:    
    void qDebugSlot1();    
    void qDebugSlot2();
void Widget::qDebugSlot1(){    
    qDebug()<<"t1";
}
void Widget::qDebugSlot2(){    
    qDebug()<<"t2";
}
connect(&t1,SIGNAL(timeout()),this,SLOT(qDebugSlot1()));   connect(&t2,SIGNAL(timeout()),this,SLOT(qDebugSlot2()));

6. Random number seed

Before using the qrand() function to generate random numbers, you generally use the qsrand() function to set the initial value. If you do not set the initial value, qrand() will generate the same set of random numbers every time you run the program. In order to generate different random numbers each time we run the program, we use qsrand () to set a different initial value.

qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));//Set random number seed
int rand = qrand() % 300;//Get random number

7. Drag event

That is, you can drag and drop the file directly into the program to open it.

Example: drag a text into the program and get the contents of the text into the program

Contains header files, using wideget window
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>

1,Function declaration:
protected:
    virtual void dragEnterEvent(QDragEnterEvent *event); //Drag event
    virtual void dropEvent(QDropEvent *event);//Drop event
2,Function implementation
void Widget::dragEnterEvent(QDragEnterEvent *event)
{
    //Determine if there are events on the widget
    if(event->mimeData()->hasUrls())
    {
        event->acceptProposedAction();  //Events to the past
    }else{
        event->ignore(); //ignore
    }
}

void Widget::dropEvent(QDropEvent *event)
{
    const QMimeData*mimeData=event->mimeData();
    if(!mimeData->hasUrls()){return;}
    QList<QUrl> urlList=mimeData->urls();//How many files have been dragged over
    for(int i=0;i<urlList.size();i++)//ergodic
    {
        qDebug()<<urlList.at(i).toLocalFile();
    }
    QFile file(urlList.at(0).toLocalFile());//Get the contents of the first file
    file.open(QIODevice::ReadOnly);
    QByteArray ba;
    ba=file.readAll();
    ui->textEdit_2->setPlainText(QString::fromLocal8Bit(ba));
}

3,Accept event
this->setAcceptDrops(true); //Accept drag events 
This refers to the of the window. There is a multi line plain text control on the window

Effect display

Extension setting (right click menu bar):

1,Define member variables
private:
    QMenu *popMenu;               //Right click pop-up menu
    QAction *adjustTimeAction;    //Content adjustment function 1 in the right-click pop-up menu
    QAction *adjustDateAction;    //Function 2
    QAction *quitAction;          //sign out

2,Function declaration
protected:
    virtual void contextMenuEvent(QContextMenuEvent *event);

3,Function implementation
void Widget::contextMenuEvent(QContextMenuEvent *event){    //Right click will trigger this event
            popMenu->clear();
            popMenu->addAction(adjustTimeAction);
            popMenu->addAction(adjustDateAction);
            popMenu->addSeparator();//Add line

            popMenu->addAction(quitAction);
            //popMenu->exec(); // Block
            popMenu->exec(QCursor::pos());
}

4,Correlating signals with slots and settings (at ui->setupUi(this);(after)
    popMenu = new QMenu(this);
    popMenu->setStyleSheet(QStringLiteral("background-color: rgb(99, 99, 99);"));
    adjustTimeAction = new QAction(this);
    adjustTimeAction->setText(("Function 1"));
    adjustDateAction = new QAction(this);
    adjustDateAction->setText(("Function 2"));
    quitAction = new QAction(this);
    quitAction->setText(("sign out"));
    connect(quitAction, SIGNAL(triggered(bool)),this, SLOT(close()));//Associated exit Action
    

 

 

Keywords: Qt

Added by Josepheuan on Wed, 26 Jan 2022 13:19:31 +0200