1.思维导图
2.一个圆形根据wsad上下左右移动,超出界限则不移动。鼠标点击和双击事件测试。
1.main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
2.mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QKeyEvent>
#include <QtDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void keyPressEvent(QKeyEvent *event)override;
void mousePressEvent(QMouseEvent *event) override;
void mouseDoubleClickEvent(QMouseEvent *event) override;
private:
Ui::MainWindow *ui;
bool moving;
};
#endif // MAINWINDOW_H
3.mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QKeyEvent>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->label->setFixedSize(50, 50);
ui->label->setStyleSheet("background-color: red; border-radius: 25px;");
ui->label->setText("");
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
int x = ui->label->x();
int y = ui->label->y();
//步长
int step = 10;
int labelWidth = ui->label->width();
int labelHeight = ui->label->height();
int windowWidth = this->width();
int windowHeight = this->height();
switch (event->key()) {
case 'W':
if (y > 0) y -= step;
break;
case 'S':
if (y + labelHeight < windowHeight) y += step;
break;
case 'A':
if (x > 0) x -= step;
break;
case 'D':
if (x + labelWidth < windowWidth) x += step;
break;
default:;
return;
}
// 更新 QLabel 的位置
ui->label->move(x, y);
}
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
QPoint pos = event->pos();
qDebug()<< "鼠标点击坐标:" << pos.x() << ", " << pos.y() <<endl;
}
QMainWindow::mousePressEvent(event);
}
void MainWindow::mouseDoubleClickEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
qDebug() << "鼠标双击" << endl;
}
QMainWindow::mouseDoubleClickEvent(event);
}