qt - 如何基于鼠标单击 qt 小部件应用程序 C++ 更新面部的眼睛?
问题描述
我有一个使用 qt creator 创建的简单 GUI,如下所示
mainwindow.cpp 看起来像这样
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QGraphicsEllipseItem>
#include <QGraphicsScene>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QGraphicsScene * scene= new QGraphicsScene(0,0,200,200);//creating scene to add graphics items
ui->graphicsView->setScene(scene);//adding scene to graphics view
QGraphicsEllipseItem * face= new QGraphicsEllipseItem(0,0,200,200);//creating face
scene->addItem(face);//adding face to scene
QGraphicsEllipseItem * lefteye= new QGraphicsEllipseItem(50,60,30,30);//creating left eye
scene->addItem(lefteye);//adding left eye to scene
QGraphicsEllipseItem * righteye= new QGraphicsEllipseItem(125,60,30,30);//creating right eye
scene->addItem(righteye);//adding right eye to scene
QGraphicsEllipseItem * lefteyeball= new QGraphicsEllipseItem(58,67,15,15);//creating left eyeball
lefteyeball->setBrush(Qt::black);//setting color of left eyeball
scene->addItem(lefteyeball);//adding left eyeball to scene
QGraphicsEllipseItem * righteyeball= new QGraphicsEllipseItem(133,67,15,15);//creating right eyeball
righteyeball->setBrush(Qt::black);//setting color of right eyeball
scene->addItem(righteyeball);//adding right eyeball to scene
}
MainWindow::~MainWindow()
{
delete ui;
}
我希望能够根据单击鼠标的位置来更新眼睛的方向,有人可以帮助实现这一点。
解决方案
您需要计算眼睛中心和光标位置之间的角度,atan2
并将瞳孔从中心移动到X
forA*cos(angle)
和 by Y
forA*sin(angle)
哪里A
是从中心的位移(恒定值)。
// eyeX, eyeY - coordinates of center of the eye
// pupilX, pupilY - coordinates of center of the pupil
double dy = eyeY - cursorY;
double dx = eyeX - cursorX;
double angle = atan2(dy, dx);
double shift = 10.0;
double pupilX = eyeX + shift * cos(angle);
double pupilY = eyeY + shift * sin(angle);
推荐阅读
- macos - 如何在 Xamarin.Mac 上创建自定义注册 Segue?
- python - pygame中的文本不会出现在屏幕上
- c# - 绑定到 DependencyObject 的 DependencyProperty 不会更新
- excel - 在文件检查时出现错误 52 但未另存为...我错过了什么?
- google-apps-script - 是否可以查询一行中的范围不为空
- docker - 如何在docker容器中操作k8s集群
- r - 使用 ggplot 显示置信区间
- r - 仅在 R 中的传单包使用的地图上显示点
- java - 从 linux 终端卸载 IntelliJ
- android - 下面的代码在将密钥转换为字节数组后返回 null