How can I draw vertical text?

Drawing vertical text can be done in several ways. The easiest way might be to create a QTextDocument [doc.qt.nokia.com] in the paintEvent() [doc.qt.nokia.com] and use setHtml() [doc.qt.nokia.com] to set the text and specify the

  1. <br>

tag to get line breaks. Another way could be to iterate over the QChars [doc.qt.nokia.com] in the QString [doc.qt.nokia.com] and position them vertically in the paintEvent() yourself. Then you would need to calculate the height between each element.

If what you want is rotated text, then you can simply rotate the painter 90 degrees.

Finally, if you are not going to draw the text yourself, then a QLabel [doc.qt.nokia.com] can easily be used to display vertical text, simply by specifying “\n” after each character.

The example below illustrates some of the possibilities:

  1. #include <QtGui>
  2.  
  3. class Widget : public QWidget
  4. {
  5. public:
  6.   Widget(QWidget *parent = 0)
  7.     : QWidget(parent)
  8.   {}
  9.  
  10.   void paintEvent(QPaintEvent *)
  11.   {
  12.     QPainter p(this);
  13. #if 1  
  14.     QTextDocument document;
  15.     document.setHtml("<br>T<br>e<br>s<br>t<br>");
  16.     document.drawContents(&p);
  17. #else  
  18.     drawRotatedText(&p, 90, width() / 2, height() / 2, "The vertical text");
  19. #endif
  20.   }
  21.  
  22.   void drawRotatedText(QPainter *painter, float degrees, int x, int y, const QString &text)
  23.   {
  24.     painter->save();
  25.     painter->translate(x, y);
  26.     painter->rotate(degrees);
  27.     painter->drawText(0, 0, text);
  28.     painter->restore();
  29.   }
  30. };
  31. int main(int argc, char **argv)
  32. {
  33.   QApplication a(argc, argv);
  34.   Widget w;
  35.   w.resize(200,200);
  36.   QString string = "t\ne\ns\nt";
  37.   QLabel label;
  38.   label.setText(string);
  39.   label.show();
  40.   w.show();
  41.   return a.exec();
  42. }
  43.  

1 comment

December 5, 2010

Picture of xsacha xsacha

Ant Farmer

The above is demonstrating a full application with rotated (any angle) text as well as some newline methods.

If it’s just vertically painted text you want, this function will suffice:

  1. void drawRotatedText(QPainter *painter, int x, int y, const QString &text)
  2. {
  3.     painter->save();
  4.     painter->translate(x, y);
  5.     painter->rotate(90); // or 270
  6.     painter->drawText(0, 0, text);
  7.     painter->restore();
  8. }

If you have a QPainter subclass, you can easily attach this to it and remove the painter argument so it appears like a normal drawText.

Write a comment

Sorry, you must be logged in to post a comment.