Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

qt - Draw rich text with QPainter

is there a way to draw fixed text that has subscripts. My goal is to have something like: "K_max=K_2 . 3"

QString equation="K_max=K_2 . 3";
painter.drawText( QRect(x, y , width, y+height), Qt::AlignLeft|Qt::AlignVCenter, equation);

I also tried formatting the text using html tags but it didn't help (tags got printed with the text):

QString equation="<p>K<sub>max</sub></p>=<p>K<sub>2</sub></p>.3"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a full example using rich text of QTextDocument.

mainWindow.cpp:

#include "mainWindow.h"

void MainWindow::paintEvent(QPaintEvent*)
{
    QPainter painter(this);
    QTextDocument td;
    td.setHtml("K<sub>max</sub>=K<sub>2</sub> &middot; 3");
    td.drawContents(&painter);
}

If you need to draw the text at specific point, translate the coordinate system of the painter before drawing:

painter.translate(QPointF(50, 50));

mainWindow.cpp - Another solution:

#include "mainWindow.h"

void MainWindow::paintEvent(QPaintEvent*)
{
    QPainter painter(this);
    QTextDocument td;
    td.setHtml("K<sub>max</sub>=K<sub>2</sub> &middot; 3");
    QAbstractTextDocumentLayout::PaintContext ctx;
    ctx.clip = QRectF( 0, 0, 400, 100 );
    td.documentLayout()->draw( &painter, ctx );
}

mainWindow.h:

#include <QtGui>

class MainWindow: public QWidget
{
protected:
    void paintEvent(QPaintEvent*);
};

main.cpp:

#include <QtGui>
#include "mainWindow.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow mainWindow;
    mainWindow.show();
    return app.exec();
}

The project file:

TEMPLATE = app
QT += gui
HEADERS = mainWindow.h
SOURCES = main.cpp mainWindow.cpp

Result:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...