官术网_书友最值得收藏!

How to do it...

Let's get started by following this example:

  1. Create a Qt Widgets Application project, open up mainwindow.h, and add the following headers:

#include <QDebug>
#include <QResizeEvent>
#include <QKeyEvent>
#include <QMouseEvent>

  1. 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);
  1. 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);
}
  1. 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";
}
  1. 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();
}
  1. 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
主站蜘蛛池模板: 平原县| 贺兰县| 万荣县| 莎车县| 吕梁市| 开封县| 来宾市| 祥云县| 比如县| 碌曲县| 石景山区| 阳高县| 奈曼旗| 西乌| 石泉县| 巨鹿县| 巧家县| 福安市| 万全县| 双峰县| 哈尔滨市| 阿坝| 黔西| 建阳市| 建阳市| 合阳县| 岑溪市| 昔阳县| 石家庄市| 万山特区| 夏邑县| 伊吾县| 铜山县| 桐梓县| 宁化县| 忻城县| 万宁市| 台南市| 西藏| 阿巴嘎旗| 顺昌县|