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

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
主站蜘蛛池模板: 和龙市| 开远市| 元江| 定州市| 关岭| 望城县| 长子县| 全州县| 漳州市| 湟源县| 大冶市| 沧州市| 福鼎市| 许昌县| 丹寨县| 丰县| 中方县| 晋中市| 休宁县| 武胜县| 柯坪县| 乌拉特后旗| 许昌市| 高要市| 江城| 西贡区| 西青区| 武乡县| 布尔津县| 大安市| 哈尔滨市| 淮安市| 仙游县| 池州市| 东光县| 峨眉山市| 黄大仙区| 大连市| 什邡市| 太白县| 临高县|