Draw rich text with QPainter

前端 未结 2 1519
独厮守ぢ
独厮守ぢ 2020-12-09 10:00

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.drawT         


        
相关标签:
2条回答
  • 2020-12-09 10:47

    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

    0 讨论(0)
  • 2020-12-09 10:54

    You may use supported Qt HTML subset to format your text. If you need to draw formatted text, you should use QTextDocument::drawContents.

    QPainter::drawText is designed for plain text without formatting, and it works much faster.

    0 讨论(0)
提交回复
热议问题