6

I have a QTextEdit widget whose contents are populated programmatically using QTextEdit.textCursor.

My plan is to let the user view the populated information in the QTextEdit, edit the text if necessary, and later print to a PDF file using QPrinter.

However, I would like to change the font size of the entire contents of the QTextEdit before allowing the user to edit the text. I just need to set the contents to a single font size; there is no need to accommodate multiple font sizes.

I have tried using QTextEdit.setFontSize(16) both before and after the textCursor operation but it doesn't seem to have any effect.

How do I change the font size of the contents of a QTextEdit widget?

sifferman
  • 2,955
  • 2
  • 27
  • 37
Chris Aung
  • 9,152
  • 33
  • 82
  • 127

2 Answers2

16

Functions like QTextEdit.setFontPointSize work on the current format. If you want to change all the font sizes at once, you need to set the size of the base font, like this:

    font = QtGui.QFont()
    font.setPointSize(16)
    self.editor.setFont(font)

Note that you can also change the relative size of the base-font using the zoomIn and zoomOut slots. The implementation of those slots changes the base-font size in exactly the same way as shown above.

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • After setPointSize, zoom have no effect ! Can not use both in the same time? – sonichy Feb 03 '17 at 02:43
  • @sonichy. It works fine for me. You must be doing something different somehow. Maybe you could try with different font-family? It could be that some fonts aren't scalable. – ekhumoro Feb 03 '17 at 03:28
  • how do you know that QTextEdit.setFontPointSize work only on the current format ? No description of this behavior in the doc http://doc.qt.io/qt-5/qtextedit.html#setFontPointSize – iMath Dec 19 '17 at 04:45
  • 1
    @iMath. The docs say: "Sets the point size of the current format". – ekhumoro Dec 19 '17 at 06:00
9

I found full solution. You should:

  • remember current textCursor
  • call selectAll
  • call setFontPointSize
  • call setTextCursor to clear selection

In C++ it can be done with the following code(it is just example but it solves your problem):

QTextCursor cursor = ui->textEdit->textCursor();
ui->textEdit->selectAll();
ui->textEdit->setFontPointSize(32);
ui->textEdit->setTextCursor( cursor );
Jablonski
  • 18,083
  • 2
  • 46
  • 47