C++ 油漆工旋转。在哪里翻译?

C++ 油漆工旋转。在哪里翻译?,c++,qt,qpainter,C++,Qt,Qpainter,我正在Qt中进行一个新项目,使用QPainter绘制一个QWidget。 问题是,当我尝试旋转QPaint时,我想要绘制的文本会从QWidget中旋转出来。 总的来说,我知道如何解决这个问题,但不知何故,我直到现在才明白。 我必须平移我的QPaint,以便将文本定位到旋转的正确位置,但我不知道如何指定应平移坐标系的点。 我的代码没有翻译: QPainter painter; float width = 40; float height = 200; float rangeMin = 0; f

我正在Qt中进行一个新项目,使用QPainter绘制一个QWidget。 问题是,当我尝试旋转QPaint时,我想要绘制的文本会从QWidget中旋转出来。 总的来说,我知道如何解决这个问题,但不知何故,我直到现在才明白。 我必须平移我的QPaint,以便将文本定位到旋转的正确位置,但我不知道如何指定应平移坐标系的点。 我的代码没有翻译:

QPainter painter;

float width = 40;
float height = 200;

float rangeMin = 0;
float rangeMax = 100;

float progress = 80;
QString format("%1/%2");
int alignmentHorizontal = Qt::AlignHCenter;
int alignmentVertical = Qt::AlignVCenter;

int fontSize = 12;
QColor backgroundColor = Qt::green;
QColor fontColor = Qt::black;

QFont font("Arial", fontSize);
QBrush backgroundBrush(backgroundColor);
QBrush transparentBrush(QColor(0,0,0,0));
QRect boundingRect = QRect(0, 0, width, height);

painter.begin(this);

painter.setFont(font);
painter.setPen(fontColor);

painter.drawRect(boundingRect);

float rectX = 0;
float rectY = 0;
float rectWidth = width;
float rectHeight = (float)height/(qAbs(rangeMin)+rangeMax)*progress;
int textRotation = 90;

painter.setBrush(backgroundBrush);
QRectF rect = QRectF(rectX, rectY, rectWidth, rectHeight);
painter.drawRect(rect);

//This is the text I want to rotate, while keeping it centerd horizontally and vertically in boundingRect.
//painter.translate(x, y);
painter.rotate(textRotation);
painter.drawText(boundingRect, alignmentHorizontal | alignmentVertical, QString(format).arg(progress).arg(rangeMax));

painter.end();
你能解释一下如何计算我需要的那一点吗

谢谢你的帮助!:)

编辑:

我像这样编辑代码:

painter.save();
painter.translate(width/2, height/2);
painter.rotate(textRotation);
painter.drawText(boundingRect, alignmentHorizontal | alignmentVertical, QString(format).arg(progress).arg(rangeMax));
painter.restore();
但它仍然在我的绘图区域外旋转。
有什么想法吗?

将画师转换到绘图区域的中心(在您的例子中,是boundingRect宽度/高度的1/2)。然后,将相对于中心进行旋转,并且文本不会从中旋转出来。

谢谢您的回答。嗯,从逻辑上讲,我认为这也应该是正确的,当我只在不旋转的情况下进行平移时,我发现效果很好,(文本从中心移动到右下角),但当我添加旋转时,文本仍然在外部绘制。请看上面的编辑。好的,你在旋转后试着向后平移了吗?哦。。很抱歉:)我以为painter.restore()会帮我的。最后一个问题。似乎在旋转之后,boundingRect以某种方式缩小了,因此文本对于它来说太长了,最后一个字符的一半超出了它。为什么?我通过添加Qt::TextDontClip解决了这个问题,但是有更好的方法吗?