2016-07-29 28 views
2

我正在Qt中使用QPainter绘制QWidget的新项目。 问题是,当我尝试旋转QPainter时,我想绘制的文本旋转出我的QWidget。 我知道如何解决一般的问题,但不知何故,直到现在我都弄不明白。 我必须翻译我的QPainter,以便将我的文本正确放置在旋转中,但是我不知道如何将该点指定到我应该翻译我的坐标系的位置。 我没有翻译代码: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(); 

但它仍然旋转我的绘图区域。 任何想法?

回答

1

将画家转换到绘图区域的中心(在您的情况下,为boundingRect的宽度/高度的1/2)。然后旋转将相对于中心完成,并且文本不会被旋转掉。

+0

感谢您的回答。从逻辑上讲,我认为这也应该是正确的,当我只在没有轮换的情况下翻译时,我发现它运行良好,(文本从中心移到右下角),但是当我添加旋转时,文本仍然绘制在外。请参阅上面的编辑。 – Flashcap20

+0

那么,你是否在旋转之后尝试翻译回来? – ypnos

+0

噢..对不起,:)我认为painter.restore()会为我做。最后一个问题。看起来在旋转boundingRect缩小之后,文本太长了,最后一个字符的一半都没有了。这是为什么? – Flashcap20