1
votes

I would like to represent on screen what a thermal printer prints like.

The printer has special formatting and can print a font with double height or double width, so I have searched something but neither Html nor Rich Text seem to have an option to do this. I also looked at QTextBlock but couldn't find something like stretch or width ratio propriety.

Is drawing the font pixel by pixel the only way?

3

3 Answers

2
votes

The question conflates two issues:

  1. How to draw stretched fonts? It's easy: change the horizontal or vertical scaling of the QPainter. Qt will do the rest for you. E.g:

    QPainter p;
    p.setTransform(QTransform(2.0, 0, 0, 1.0, 0, 0)));
    p.drawText(0, 0, "STRETCHED");
    
  2. How to express stretch in rich text? That's not directly possible without modifying Qt sources - although such modifications would be quite simple. Otherwise, you can pre-render the text to an image, and use the image instead of text.

1
votes

In addition to Kuba Obre's suggestion, I have also found that QFont has the method setStretch() that does exactly what I need.

Then there are two ways to use that stretched QFont to render a piece of document:

  1. create a Rich Text Document (QTextDocument). I didn't try, but the procedure seems to be the following (it is easier to create a new RTF rather than load the whole text and then edit the desired pieces of text).
    QTextCursor::setCharFormat(const QTextCharFormat & format), using QTextCharFormat::setFontStretch(int factor) directly (no need to pass through QFont). Then QTextCursor::insertText(const QString & text).

  2. use QPainter with the stretched font. QPainter::setFont(const QFont & font) then QPainter::drawText()

The second method is faster, but need to struggle with coordinates. The first method is longer but renders like a text document. I will evaluate which one is better for me.

Hope it is useful to others, a.

1
votes

This is a working example using QTextDocument (Rich text format creation)

Let's have a QTextBrowser widget in our ui, called browser

QFont font; //we can optionally .setFamily()
QTextDocument * rtf = new QTextDocument(this);
//QTextCursor is needed to write into the TextDocument (otherwise it is readonly)
QTextCursor * editor = new QTextCursor(rtf);
QTextCharFormat format = QTextCharFormat();
editor->insertText("Normal Text\n");
//prepare font for wide text
font.setStretch(200);
format.setFont(font);
editor->setCharFormat(format);
editor->insertText("WIDE text\n");
//prepare font for narrow text
font.setStretch(50);
format.setFont(font);
editor->setCharFormat(format);
editor->insertText("narrow text\n");

ui->browser->setDocument(rtf);