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

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
主站蜘蛛池模板: 喀喇| 漳州市| 敦化市| 昔阳县| 横峰县| 西华县| 公安县| 横峰县| 绥宁县| 太康县| 七台河市| 额尔古纳市| 丰顺县| 安乡县| 宝应县| 太原市| 凤山县| 张家港市| 房产| 定西市| 新安县| 阳谷县| 吴旗县| 五指山市| 黄浦区| 仙桃市| 汽车| 益阳市| 惠东县| 涞水县| 遵义市| 海兴县| 罗江县| 射阳县| 新密市| 淳化县| 天津市| 青州市| 甘谷县| 马边| 克什克腾旗|