首页 > 解决方案 > 如何基于鼠标单击 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;
}

我希望能够根据单击鼠标的位置来更新眼睛的方向,有人可以帮助实现这一点。

标签: qtqt5qgraphicsviewqgraphicssceneqgraphicsitem

解决方案


您需要计算眼睛中心和光标位置之间的角度,atan2并将瞳孔从中心移动到XforA*cos(angle)和 by YforA*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);

推荐阅读