Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate text for drawText?

I would like to rotate the text 45 degrees?

QFont font;
font.setPixelSize(12);

//grid
for(int i = 0; i < 10; i++){
    painter->drawLine(100, 100 + i * 800/9, 900, 100 + i * 800/9);
    str = QString::number((double)9 - i, 'd', 1);
    painter->setFont(font);
    painter->drawText(75, 100 + i * 800/9 - 6, 40, 40, 1, str);
}
like image 405
jdl Avatar asked Jul 23 '13 20:07

jdl


4 Answers

Insert painter->rotate(45); before painter->drawText(75, 100 + i * 800/9 - 6, 40, 40, 1, str); and painter->rotate(-45); after (to restore the rotation angle of the coordinate system):

painter->rotate(45);
painter->drawText(75, 100 + i * 800/9 - 6, 40, 40, 1, str);
painter->rotate(-45);

Depending on if you mean 45 degrees clockwise or anti-clockwise you may need to negate the rotation angles.

After you rotate the coordinate system, everything you paint will be painted rotated until you restore the painter. A convenient way of saving and restoring the state of the painter is using QPainter::save() and QPainter::restore().

like image 158
Daniel Hedberg Avatar answered Oct 29 '22 10:10

Daniel Hedberg


painter->save(); // saves current painter state
// painter->rotate(45); clockwise rotation 
// painter->rotate(-45); counter clockwise rotation
painter->restore(); // restores painter state
like image 32
Hesam Qodsi Avatar answered Oct 29 '22 11:10

Hesam Qodsi


In order to rotate your text (and any other drawable object) drawn by painter just call

painter->rotate(yourAngle);

before

painter->drawText();

If you wish to return to previous state call rotate again.

painter->rotate(-yourAngle);
like image 39
Mateusz Andrzejewski Avatar answered Oct 29 '22 11:10

Mateusz Andrzejewski


Why making such a simple task so complicated?!!!

void CustomLabel::paintEvent(QPaintEvent* e)
{
    QPainter painter(this);

    painter.translate(m_rect.center());
    painter.rotate(m_rotation);
    painter.translate(-m_rect.center());
    painter.drawText(m_rect, Qt::AlignHCenter | Qt::AlignVCenter, m_text);

    QWidget::paintEvent(e);
}

any time the container of CustomLabel changes it size you can set the m_rect or use the this->rect() itself.

like image 1
Mohammad Rahimi Avatar answered Oct 29 '22 11:10

Mohammad Rahimi