qt event



1 Small Project
2 Basic Introduction
Events are issued by the system or Qt itself at different times. When the user presses the mouse, presses the keyboard, or when the window needs to be repainted, a corresponding event is emitted. Some events are emitted in response to user actions, such as keyboard events; others are emitted automatically by the system, such as timer events.

Events are the basic concepts of what we usually call "event drive" programming. Events occur so that program code does not execute in the original linear order. Think about it, since the beginning of the C language, our programs have been executing code in a linear order: after this statement is executed, the next statement is executed; after this function is executed, the next function is executed. This "batch"-like programming style is clearly not suitable for handling complex user interactions. Let's imagine the scenario of user interaction: we designed a bunch of functions on the interface, the user clicked "Open File", and then started to perform the operation of opening the file; the user clicked "Save File", and then started to execute the operation of saving the file. operate. We don't know what the user wants to do, so we can't predict which function will be called next. If we design a "save file as" action, if the user doesn't click, this action will never be called. This is the so-called "event-driven", the execution sequence of our program is no longer linear, but one by one event-driven program continues to execute. Without the event, the program will block there and execute no code.

In Qt, the concept of events seems to be similar to signals and slots. Indeed, in general, when using Qt components, we don't focus primarily on events. Because in Qt, we care more about a signal associated with an event. For example, for the mouse click of QPushButton, we don't need to care about the mouse click event, but the issuance of its clicked() signal. This is different from some other GUI frameworks: in Swing, all you need to care about is the click event of the JButton's ActionListener. It can be seen that compared to other GUI frameworks, Qt gives us an additional choice: signals and slots.

However, events and signal slots in Qt are not interchangeable. Signals are emitted by specific objects and then immediately handed over to the slot connected by the connect() function for processing; for events, Qt uses an event queue to maintain all emitted events, and when new events are generated, they will be appended to the end of the event queue. After the previous event is completed, the latter event is taken out for processing. However, when necessary, Qt events can also be processed directly without entering the event queue. Once the signal is sent, the corresponding slot function will be executed. However, events can be filtered using an "event filter", which performs additional processing for some events and does not care about others. In general, if we use components, we care about signals and slots; if we customize components, we care about events. Because we can change the default action of the component through events. For example, if we want to customize an EventLabel that can respond to mouse events, we need to rewrite QLabel's mouse events to do what we want, and possibly send out a button-like clicked() signal at the right time ( If we want this EventLabel to be used by other components) or other signals.

We also briefly mentioned earlier that a Qt program needs to create a QCoreApplication object in the main() function, and then call its exec() function. This function is what starts Qt's event loop. After executing the exec() function, the program will enter the event loop to listen for the application's events. When an event occurs, Qt will create an event object. All event classes in Qt inherit from QEvent. After the event object is created, Qt passes the event object to QObject's event() function. The event() function does not handle events directly, but dispatches to a specific event handler according to the type of event object. We will elaborate on this in later chapters.

In the parent class QWidget of all components, many callback functions for event processing are defined, such as keyPressEvent(), keyReleaseEvent(), mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(), mouseReleaseEvent(), etc. These functions are protected virtual, that is, we can reimplement these functions in subclasses. Here's an example:

class EventLabel : public QLabel
{
protected:
    void mouseMoveEvent(QMouseEvent *event);
    void mousePressEvent(QMouseEvent *event);
    void mouseReleaseEvent(QMouseEvent *event);
};

void EventLabel::mouseMoveEvent(QMouseEvent *event)
{
    this->setText(QString("<center><h1>Move: (%1, %2)</h1></center>")
                  .arg(QString::number(event->x()), QString::number(event->y())));
}

void EventLabel::mousePressEvent(QMouseEvent *event)
{
    this->setText(QString("<center><h1>Press: (%1, %2)</h1></center>")
                  .arg(QString::number(event->x()), QString::number(event->y())));
}

void EventLabel::mouseReleaseEvent(QMouseEvent *event)
{
    QString msg;
    msg.sprintf("<center><h1>Release: (%d, %d)</h1></center>",
                event->x(), event->y());
    this->setText(msg);
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    EventLabel *label = new EventLabel;
    label->setWindowTitle("MouseEvent Demo");
    label->resize(300, 200);
    label->show();

    return a.exec();
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

When we compile and run the above code, we can understand the usage of related events.
EventLabel inherits QLabel and covers three functions: mousePressEvent(), mouseMoveEvent() and MouseReleaseEvent(). We didn't add any function, just display the current mouse coordinate value on this Label when the mouse is pressed (press), mouse moved (move) and mouse released (release). Since QLabel supports HTML code, we directly use HTML code to format text.
QString's arg() function can automatically replace placeholders that appear in QString. Its placeholder starts with %, followed by the position of the placeholder, such as %1, %2.

1 QString(“[%1, %2]”).arg(x, y);
The statement will replace %1 with x and %2 with y, so the QString generated by this statement is [x, y].
In the mouseReleaseEvent() function, we use another QString constructor. We use the C-like formatting function sprintf() to construct the QString.
Run the above code, when we click the mouse, the current coordinate value of the mouse will be displayed on the label.

Why can the mouse coordinate value be displayed in the mouseMoveEvent() function after the mouse is clicked? This is because there is a mouseTracking property in QWidget, which is used to set whether to track the mouse. mouseMoveEvent() is only emitted when the mouse is tracked. If mouseTracking is false (which is the default), the component cannot be tracked until after at least one mouse click, i.e. a mouseMoveEvent() event can be emitted. If mouseTracking is true, then mouseMoveEvent() can be emitted directly. Knowing this, we can set it directly in the main() function:

1
2
3
4
5   EventLabel *label = new EventLabel;
label->setWindowTitle("MouseEvent Demo");
label->resize(300, 200);
label->setMouseTracking(true);
label->show();
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

This way there is no such problem.

QT various events, basically the QWidget class has been written for you, but they are all virtual functions, the role is to let you rewrite. E.g:

bool MyWidget::event(QEvent *ev) {      if(ev->type() == QEvent::MouseButtonPress)             ……
        return QWidget::event(ev); }   
  
  
  • 1
  • 2

Description: You can detect whether the mouse is pressed, but we generally do not use this function, because there are too many things to deal with, usually use specific functions such as mousePressEvent paintEvent and so on.

3 Main methods
3.1 Detect whether the window is closed

void MyWidget::closeEvent(QCloseEvent *) {     qDebug() << "closeEvent"; }
  
  
  • 1

3.2 Detect mouse press and release to move

    void MyWidget::mousePressEvent(QMouseEvent *ev) {     QPoint pt = ev->pos();     qDebug() << pt;     if(ev->button() == Qt::LeftButton)     {      }     if(ev->modifiers() == Qt::ShiftModifier)     {         qDebug() << "shift press";     }

void MyWidget::mouseReleaseEvent(QMouseEvent *) {} void MyWidget::mouseMoveEvent(QMouseEvent *) {     static int i=0;     qDebug() << "mouse move"<< i++; }
  
  
  • 1
  • 2
  • 3

3.3 Keyboard events

void MyWidget::keyPressEvent(QKeyEvent *ev) {     ev->modifiers();     int key = ev->key();     qDebug() << key;     char a = key;     qDebug() << (char)a; }
  
  
  • 1

Reprinted from: https://blog.csdn.net/gusgao/article/details/48861765



1 Small Project
2 Basic Introduction
Events are issued by the system or Qt itself at different times. When the user presses the mouse, presses the keyboard, or when the window needs to be repainted, a corresponding event is emitted. Some events are emitted in response to user actions, such as keyboard events; others are emitted automatically by the system, such as timer events.

Guess you like

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