- Qt5 C++ GUI Programming Cookbook
- Lee Zhi Eng
- 248字
- 2021-07-02 12:17:58
How to do it...
Let's get started by following this example:
Create a Qt Widgets Application project, open up mainwindow.h, and add the following headers:
#include <QDebug>
#include <QResizeEvent>
#include <QKeyEvent>
#include <QMouseEvent>
- Then, declare these functions in mainwindow.h:
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void resizeEvent(QResizeEvent *event);
void keyPressEvent(QKeyEvent *event);
void keyReleaseEvent(QKeyEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
- After that, open up mainwindow.cpp and add the following code to the class constructor:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
this->setMouseTracking(true);
ui->centralWidget->setMouseTracking(true);
}
- Then, define the resizeEvent() and keyPressedEvent() functions:
void MainWindow::resizeEvent(QResizeEvent *event) {
qDebug() << "Old size:" << event->oldSize() << ", New size:" << event->size();
}
void MainWindow::keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Escape) {
this->close();
}
qDebug() << event->text() << "has been pressed";
}
- Continue to implement the rest of the functions:
void MainWindow::keyReleaseEvent(QKeyEvent *event) {
qDebug() << event->text() << "has been released";
}
void MainWindow::mouseMoveEvent(QMouseEvent *event) {
qDebug() << "Position: " << event->pos();
}
void MainWindow::mousePressEvent(QMouseEvent *event) {
qDebug() << "Mouse pressed:" << event->button();
}
void MainWindow::mouseReleaseEvent(QMouseEvent *event) {
qDebug() << "Mouse released:" << event->button();
}
- Build and run the program. Then, try and move the mouse around, rescale the main window, press some random keys on your keyboard, and finally press the Esc key on your keyboard to close the program. You should be seeing debug texts similar to the ones that are being printed out on the application output window:
Old size: QSize(-1, -1) , New size: QSize(400, 300)
Old size: QSize(400, 300) , New size: QSize(401, 300)
Old size: QSize(401, 300) , New size: QSize(402, 300)
Position: QPoint(465,348)
Position: QPoint(438,323)
Position: QPoint(433,317)
"a" has been pressed
"a" has been released
"r" has been pressed
"r" has been released
"d" has been pressed
"d" has been released
"\u001B" has been pressed