逛奔的蜗牛

我不聪明,但我会很努力

   ::  :: 新随笔 ::  ::  :: 管理 ::

Drawing vertical text can be done in several ways. The easiest way might be to create a QTextDocument in the paintEvent() and use setHtml() to set the text and specify the <br> tag to get line breaks. Another way could be to iterate over the QChars in the QString 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 can easily be used to display vertical text, simply by specifying after each character.

The example below demonstrates some of the possibilities:

#include <QtGui>

class Widget : public QWidget
{

public:
	Widget(QWidget *parent = 0)
		: QWidget(parent)
	{
	}

	void paintEvent(QPaintEvent *)
	{
		QPainter p(this);
#if 1	
		QTextDocument document;
		document.setHtml("<br>T<br>e<br>s<br>t<br>");
		document.drawContents(&p);



#else	
		drawRotatedText(&p, 90, width() / 2, height() / 2, "The vertical text");
#endif
	}


	void drawRotatedText(QPainter *painter, float degrees, int x, int y, const QString &text)
	{

		painter->save();
		painter->translate(x, y);
		painter->rotate(degrees);
		painter->drawText(0, 0, text);
		painter->restore();
	}
};

int main(int argc, char **argv)
{
	QApplication a(argc, argv);
	Widget w;
	w.resize(200,200);
	QString string = "t
e
s
t ";
	QLabel label;
	label.setText(string);
	label.show();
	w.show();
	return a.exec();
}
posted on 2009-05-05 00:23 逛奔的蜗牛 阅读(2606) 评论(0)  编辑 收藏 引用 所属分类: Qt