[Solved] How to change the default color of QTextDocument PlainText



  • Hi everybody,

    I'm trying to find a way to change the default text color of QTextDocument.
    Unfortunately Richtext is not an option for me.
    I have to go for plainText. I would appreciate any tips.

    Thanks for the help.

    Best regards
    messi

    Here is an example.
    I have tried various solutions but with no success.

    1. Attempt:
    Change the blockformat:
    texDocument.firstBlock().blockFormat().setForeground(QBrush(Qt::green,Qt::SolidPattern));

    2. Attempt:
    Change the penn and the brush od the painter:
    painter.setBrush(QBrush(Qt::green,Qt::SolidPattern));
    painter.setPen(QColor(Qt::red));

    //Example

    @#include <QtGui>
    #include <QString>

    const QString text("BlaBla\nWuWu");

    int main(int argv, char *args[])
    {
    QApplication app(argv, args);
    QWidget mw;

    QTextDocument texDocument;
    texDocument.setDefaultFont( QFont("Libaration", 12, -1, true ) );
    texDocument.setPlainText(text);
    
    QPixmap pixmap(texDocument.size().toSize());
    pixmap.fill( Qt::transparent );
    QPainter painter( &pixmap );
    
    texDocument.drawContents(&painter, pixmap.rect());
    
    QPushButton button(&mw);
    button.setIcon(QIcon(pixmap));
    button.setIconSize(pixmap.size());
    
    mw.resize(100, 70);   
    mw.show();
    
    return app.exec(&#41;;
    

    }@



  • I found a solution. The problem is, that QTextDocumentLayout::draw takes a parameter QAbstractTextDocumentLayout::PaintContext ctx. This one is defined inside QTextDocument.

    Now I wrote a new drawContents function which takes an additional parameter QTextDocument.
    The example from above works with this additional function.

    @void drawContents(QTextDocument *td, QPainter *p, const QRectF &rect)
    {
    p->save();
    QAbstractTextDocumentLayout::PaintContext ctx;

    ctx.palette.setColor(QPalette::Text, p->pen().color());
    
    if (rect.isValid()) 
    {
        p->setClipRect(rect);
        ctx.clip = rect;
    }
    
    td->documentLayout()->draw(p, ctx);
    p->restore();
    

    }@


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.