我的项目中有线条画家小部件。因此,我必须开发算法,当用户按下Shift键时,它允许直线校正。我在Photoshop和Paint中看到过类似的东西。 但我自己的方法不起作用。我正在使用Qt库。 代码在这里。 drawedPoints_是QPointF的QList
void GesturePaintSurface::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
isDrawingFinished_ = false;
drawedPoints_.clear();
firstPoint_ = event->pos();
drawedPoints_.append(firstPoint_);
}
else
{
event->ignore();
isDrawingFinished_ = true;
}
}
void GesturePaintSurface::mouseMoveEvent(QMouseEvent *event)
{
if (!isDrawingFinished_)
{
if (isShiftPressed_)
{
QPoint newPoint;
if (abs(drawedPoints_.last().rx() - event->pos().rx()) < 5)
{
newPoint.rx() = firstPoint_.x();
newPoint.ry() = event->pos().y();
}
else
{
newPoint.rx() = event->pos().x();
newPoint.ry() = firstPoint_.y();
}
drawedPoints_.append(newPoint);
}
else
drawedPoints_.append(event->pos());
repaint();
}
}
对不起我的语言。提前谢谢!
答案 0 :(得分:0)
第一个问题是每次鼠标移动时你都会附加点!第二个问题是制作垂直或水平线的这种情况是错误的。
应该是这样的:
void GesturePaintSurface::mouseMoveEvent(QMouseEvent *event)
{
if (!isDrawingFinished_)
{
QPoint newPoint;
if (event->modifiers().test(Qt::ShiftModifier)) {
newPoint = drawedPoints_.last();
if (qAbs(newPoint.x()-event->x())<qAbs(newPoint.y()-event->y())) {
newPoint.setY(event->y());
} else {
newPoint.setX(event->X());
}
} else {
newPoint = event->pos();
}
if (drawedPoints_.count()>1) {
drawedPoints_.last() = newPoint;
} else {
drawedPoints_.append(newPoint);
}
update(); // update is better then repaint!
}
}