Qt mouse click event handling: press the Escape key to exit the program

Create project

Qt Getting Started Practical Tutorial (Table of Contents)

First, create a Qt default window program named QtKeyEscape.

Reference: Qt Creator creates Qt default window program

Qt responds to keyboard Escape event

Open Qt Creator >> Edit >> Project >> Headers >> mainwindow.h

右键 class MainWindow >> Refactor >> Insert Virtual Function of Base Classes

As shown below:

Select QWidget >> keyPressEvent

Insertion options:

>> Insert definitions in implementation file >> OK

As shown below:

Qt press Escape key to exit the program

Open Sources >> mainwindow.cpp

Add header file include

>> #include <QKeyEvent>

Exit current program

For single-window Qt programs, you only need to close the current window.

To close the current window, just use this->close(); to close and exit the current window.

The specific implementation is as follows: Add the following member function implementation to your window class.

Exit code in MainWindow:: keyPressEvent :

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key_Escape)
    {
        this->close();
    }
}

When you run the program, a window pops up:

Press the Escape key and the window disappears (the program exits).

Code download

Baidu cloud

Link: https://pan.baidu.com/s/1ZTsZqW2nLXOctb58_1G4Pw

Extraction code: 1234

Gitee code cloud

QtKeyEscape · CalmReason/learn-qt-with-code - Code Cloud - Open Source China (gitee.com)

Guess you like

Origin blog.csdn.net/ClamReason/article/details/132678950