QPainter 旋转。在哪里翻译?

QPainter rotation. Where to translate?

我正在用 Qt 开发一个新项目,使用 QPainter 绘制一个 QWidget。 问题是,当我尝试旋转 QPainter 时,我想要绘制的文本旋转出我的 QWidget。 我知道一般如何解决这个问题,但不知何故直到现在我才弄清楚。 我必须翻译我的 QPainter,以便将我的文本正确定位以进行旋转,但我不知道如何将那个点指定到我应该翻译我的坐标系的位置。 我没有翻译的代码:

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();

但它仍然旋转出我的绘图区域。 有什么想法吗?

将 painter 平移到绘图区域的中心(在您的例子中,是 boundingRect 的 1/2 width/height)。然后旋转将相对于中心完成,文本不会旋转出来。