Qt FontMetrics boundingrect vs Geometry rect - qt

QString sText1 = "Sample Text890\nSample Text 890";
QString sText2 = "Sample Text890 Sample Text 890";
label1_->setText(sText1);
label2_->setText(sText2);
label1_->setWordWrap(false);
label2_->setWordWrap(false);
label1_->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
label2_->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
Numbered boxes show metrics/information of corresponding labels just above them.
case 1: BoundingRect width is NOT equal to label widthx2
BoundingRectHeight is equal to label widthx2
case 2: BoundingRect width and height matches with label's width and height
case 3: No clue how boundingrect and label geometry are related!!
case 4: No clue how boundingrect and label geometry are related!!
case 5:
QString sText1 = "Sample Text890\nSample Text 890";
QString sText2 = "Sample Text890 Sample Text 890";
label1_->setWordWrap(true);
label2_->setWordWrap(true);
Question: I'm confused how font's bounding rect and label's geometry are related.
EDIT: I have updated case 5 and case 6 with label word wrap TRUE.

From the boundingRect(text) documentation:
Newline characters are processed as normal characters, not as linebreaks.
So, considering the above, case 1 and 2 have the same height because, since the new line character does not create a new line. The width is different because a new line character has a different width.
Case 3 and 4 have the same bounding rect, which is the smallest possible width based on the given rect and text option. Since the base rect has no width and the option is to wrap words, you'll get a rectangle that is wide as the "longest" word (based on the font), while the height depends on the widths of the other words in the given text: you'll get a line for each word, unless two or more words can fit the above maximum width; the height depends on the line height multiplied the final line count.
Consider the original strings:
sText1 = 'Sample Text890\nSample Text 890'
sText1 = 'Sample Text890 Sample Text 890'
Case 1
The processed string is actually:
Sample Text890*Sample Text 890
Note: " * " refers to the newline character, it's not actually the * character.
The width is that of the whole string.
The negative y is because the drawing considers the origin (0, 0) for the baseline: y is the negative fontMetrics.ascent().
In this case, the QLabel has a different height because it does consider the newline character.
Case 2
The processed string is used as it is (one line), so the label size matches the font metrics. The result is probably as using a QRect at (0, 0), sized with horizontalAdvance() and height().
Case 3 and 4
Since the source rectangle has no width and word wrapping is enabled, the text will be laid out in order to fit it by extending the width until wrapping is possible; the final processed text becomes the following:
Sample
Text890
Sample
Text
890
Which makes sense, since the height for case 1 and 2 is 41 and the height of case 3 and 4 is about 5 times that value.
Note that results may change depending on the font, and do not depend on the length of the string. For instance, consider a peculiar font that has numbers that are extremely wide (about 3 times a normal character); the resulting text could be this:
Sample
Text890
Sample Text
890
That would be because 890 is very wide with that peculiar font, and the line Text890 becomes wider than Sample Text, which then will fit in a single line:
Relations with the QLabel size
By default, QLabel does not wrap text (see the wordWrap property), so case 3 and 4 are not related because you explicitly specified that option for the font metrics. That said, you can get consistent result if you understand how text layout works.
For instance, to get a consistent bounding rect, use a very big rectangle as source:
QRect rect1 = fontMetrics.boundingRect(QRect(0, 0, 2000, 2000), Qt::TextWordWrap, sText1);
Which will return a size equal to the label basic sizeHint(). Obviously, since the source rectangle is that big, the word wrap option is useless, and you'll get the same result using 0 instead of Qt::TextWordWrap.
On the other hand, you can have the same result of the bounding rect that you got with the empty QRect, using the minimumSizeHint() and with wrapping enabled:
label.setWordWrap(true)
QSize minWidth = label.minimumSizeHint().width()
QRect boundingRect(0, 0, minWidth, label.heightForWidth(minWidth))
Remember, though, that using word wrapping in QLabel can have counter intuitive and unwanted results; while those results might seem unexpected, they actually are expected (see the note about layout issues: Qt layout management is not the same as a webpage, and the priority is always for all widgets, even if it's for the sake of a label. If the label must support wrapping but it's also placed in a complex layout, you need to explicitly set a reasonable minimum size (width, height, or both) whenever the layout also contains widgets that can adapt their size based on the overall available size; see the related note below.
Final considerations
QLabel uses parts of the Qt rich text processing framework, specifically QTextDocument, its document layout and the basic QTextLayout; unfortunately, probably due to performance reasons, all those components are private for QLabel; the only way to reliably compute a QLabel size (in the rare case for which this should be really needed) is to have deep knowledge of the above aspects;
QFontMetrics and QTextLayout are closely related: the former uses the latter to compute the size of laid out text (boundingRect(QRect, flags, text)), and vice versa for computing basic glyph sizes;
Qt layout managers will try their best to fit a word-wrapped label in the layout, but, as explained above, results may vary;
word-wrapped text should not be part of a layout: while this might be considered a Qt limitation, it's almost always a bad choice from the UX perspective (remember, a program is not a webpage, which is scrollable by nature); those texts should probably be put in a scroll area, so eventually consider using a QTextEdit or QPlainTextEdit set as readOnly and eventually a transparent background to make it look "like a label";
any padding/border/margin set with setContentsMargins() or QSS (Qt style sheets) must be added manually when trying to use font metrics;

Related

get the exact height of QTextDocument in pixels

I need to get the actual height of QTextDocument in order to be able to set the containing QPlainTextEdit to a minimum height (while keeping its width constant) so that it shows the whole content without the vertical scrollbar. I tried to follow this question (closed with with accepted answer) How do I determine the height of a QTextDocument? but it does not do what it promises.
A piece of code:
from PyQt5.QtWidgets import QApplication, QPlainTextEdit
app = QApplication([])
w = QPlainTextEdit()
w.setPlainText("Hello!")
print(w.document().size())
w.setPlainText("Hello!\nHello again!")
print(w.document().size())
prints out:
PyQt5.QtCore.QSizeF(35.0, 1.0)
PyQt5.QtCore.QSizeF(64.0, 2.0)
It seems that the width is measured correctly in pixels but the height just shows the number of lines instead of pixels. I think multiplying it with font pixel metric height does not help because there can be mixed formatting (in general it can be a rich text / HTML) and line spacing, document margins and maybe some other complicated stuff based on implementation details... etc.
So is there a way out?
So I finally found a solution but it is really ugly. If anyone knows anything better, please publish it.
from PyQt5.QtWidgets import QApplication, QPlainTextEdit
app = QApplication([])
w = QPlainTextEdit()
# test various formatting
w.appendHtml("<h1>Hello!</h1>")
w.appendHtml("<b>Hello!</b>")
w.appendPlainText("Hello!")
doc = w.document()
layout = doc.documentLayout()
h = 0
b = doc.begin()
while b != doc.end():
h += layout.blockBoundingRect(b).height()
b = b.next()
# magic formula: I do not know why the document margin is already
# once included in the height of the last block, and I do not know
# why there must be the number 1 at the end... but it works
w.setFixedHeight(h + doc.documentMargin() + 2 * w.frameWidth() + 1)
w.show()
app.exec_()
So this should show the box without scroll bar. If you decrease the height by 1, the scroll bar appears. This should work with any number of lines, document margins, frame widths, formatting etc. Hopefully.
Shot in the dark without testing
Have you looked # pageSize?
From the docs:
This property holds the page size that should be used for laying out the document
The units are determined by the underlying paint device. The size is
measured in logical pixels when painting to the screen, and in points
(1/72 inch) when painting to a printer.
By default, for a newly-created, empty document, this property
contains an undefined size.
If you set the pageSize, as directed by the other thread, I'd expect you'd get the value out in the pixels that QPlainTextEdit::setMinimumHeight needs.

Get QPainter drawn text dimensions

I want to draw some text using QPainter::drawText command.
In order to set its position properly I need to know the dimension of drawn string in pixels.
Is there a way to know pixel dimension of the string? Possibly without drawing it before?
The QFontMetrics class has a method just for this purpose: boundingRect().
From the Qt docs (http://doc.qt.io/qt-5/qfontmetrics.html#boundingRect-2):
Returns the bounding rectangle of the characters in the string specified by text.
Note that the bounding rect only provides the width of drawn text, the width() function provides the width of trailing spaces as well. Also from the Qt docs:
boundingRect() returns a rectangle describing the pixels this string will cover whereas width() returns the distance to where the next string should be drawn.

Tkinter Grid Columnspan ignored

Consider the following python script
#!/usr/bin/env python
from Tkinter import Tk, Label
width = SOME_VALUE_HERE
root = Tk()
label1 = Label(root, text='1 columns wide')
label2 = Label(root, text='%i columns wide' % width)
label1.grid()
label2.grid(row=0,column=1,columnspan=width)
root.mainloop()
When I run this, no matter what value is set for 'SOME_VALUE_HERE', both labels take up half the window, regardless of whether or not Grid.columnconfigure is called, or the sticky parameter is used in grid().
Unless I've overlooked something, I would have thought that setting the columnspan would force the second label to be 'SOME_VALUE_HERE' times as wide as the first.
Have I misunderstood how grid works? How would I go about achieving this behavior?
By default, empty grid column are zero width, so you described the following table. Grid geometry manager will by default try to optimize the screen real estate used by your application. It will integrate all the constraint and produce the fittest layout.
+---------------+---------------++++
| 0 | 1 |||| <-- 2,3,4 empty, 0 width
+---------------+---------------++++
| 1 column wide | 4 column wide |
+---------------+---------------++++
To provide strict proportional column width, you have to use the uniform option of columnconfigure. uniform takes an arbitrary value to designate the group of the column that share these proportions, and the weight argument is used to properly handle widget resizing.
label1.grid(row=0, column=0)
label2.grid(row=0,column=1, columnspan=width)
for i in range(width+1):
root.grid_columnconfigure(i, weight=1, uniform="foo")
Note that with only these two labels, you could achieve the same layout by adjusting the width of column 1. Differences will occur still while you populate column 2,3,4...
label2.grid(row=0,column=1) #no columnspan
root.grid_columnconfigure(0, weight=1, uniform="foo")
root.grid_columnconfigure(1, weight=width, uniform="foo")
When you put something in column 1 with a columnspan of two (or more) that means it will be in column 1 and column 2 (etc). However, if there is nothing controlling the width of a column, that column will have a width of zero. You need to force column 2 to have a widtheither by putting something in there, giving it a minsize, or forcing uniform columns.
When I look at your code, I can't guess how wide you think column 2 should be, and neither can the computer.
I had a similar problem only to discover that the elements are limited by the widest widget. We can safely say that Tkinter is configured to make your app uniform in that it should be a regular repeating square/triangular structure. Solution to override default options.
With the Tkinter's automatic optimization in mind, play with the width and height of largest widget (grid box) and relate the other boxes to it proportionally.
Using the above method use columnspan to adjust the width.
Configure the widths by use of columnconfigure()

Getting QGraphicsTextItem length?

Is there anyway to calculate the text's length when TextWidth = -1?.
I have a rectangle that has a QGraphicsTextItem in it, and I want to change the rectangle's width when characters exceed the rectangle.
I found this post by stopping on the same problem.
i'm using text->boundingRect().width()to get the width.
Perhaps it helps anybody
textWidth = -1 means, that
"[...] the text will not be broken into
multiple lines unless it is enforced
through an explicit line break or a
new paragraph."
(QTextDocument::textWidth())
So, if you want to get the length of your QGraphicsTextItem you can't use textWidth, but instead you need the actual length of the String within this QGraphicsTextItem. Have a look at QGraphicsTextItem::toPlainText(), which returns a QString. Call size() on that string.
int length = my_graphics_text_item.toPlainText().size()
Now you have the number of characters in this string and can implement a resize function to make your rectangle grow, when there are too many characters. It's a kind of workaround, but I hope it helps solving your problem.
You could also create a QFontMetrics([font of your QGraphicsTextItem]) instance and call its width(QString) function to obtain the width of the passed string in pixels, were it drawn in the specified fontfamily/-size/-weight.
Just obtaining the character count is only reasonable when using a monospaced font. In all other cases it's not a good idea.

Is there a way to make drawText() update a QPicture's bounding rect?

Drawing on a QPicture should update its bounding rect. Like this:
>>> picture = QPicture()
>>> painter = QPainter(picture)
>>> picture.boundingRect()
QRect(0,0,0,0)
>>> painter.drawRect(20,20,50,50)
>>> picture.boundingRect()
QRect(20,20,50,50)
But if I draw text on it, the bounding rect isn't updated:
>>> picture = QPicture()
>>> painter = QPainter(picture)
>>> picture.boundingRect()
QRect(0,0,0,0)
>>> painter.drawText(10,10, "Hello, World!")
>>> picture.boundingRect()
QRect(0,0,0,0)
Obviously, it doesn't update the bounding rect.
Is there a way to make it repsect drawn text or do I have to do it manually? (Not too hard, but I hope that Qt can assist me here.)
Take a look at these overload methods, where you must specify the Bounding Rectangle after the text parameter (which is apparently different than the rectangle in the first argument's position):
Draws the given text within the
provided rectangle according to the
specified flags. The boundingRect (if
not null) is set to the what the
bounding rectangle should be in order
to enclose the whole text.
QPainter.drawText (1), QPainter.drawText (2)
Update:
It appears if you want to generate a bounding rectangle for the drawText() method in advance, you just call the boundingRect() method on QPainter, which does the following:
Returns the bounding rectangle of the
text as it will appear when drawn
inside the given rectangle with the
specified flags using the currently
set font(); i.e the function tells you
where the drawText() function will
draw when given the same arguments.
If the text does not fit within the
given rectangle using the specified
flags, the function returns the
required rectangle.
QPainter.boundingRect
I linked to BoundingRect with QRectF output, but the information applies to the other versions as well.
So basically, pass the result of QPainter.boundingRect() into the boundingRect parameter of the QPainter.drawText() method (the second QRect argument).
Update 2:
I APOLOGIZE PROFUSELY for being so damn dense. I forgot that drawText works differently in PyQt than in Qt. The bounding rectangle is RETURNED by the drawText function (not passed in like Qt) and in addition, you have to specify alignment flags before you get a bounding rectangle given back to you. (I even included the p.end() as per Aaron Digulla's comment):
pic = Qt.QPicture()
p = QtGui.QPainter(pic)
brect = p.drawText(10,10,200,200, QtCore.Qt.AlignCenter, "blah")
p.end()
print brect
print pic.boundingRect()
Here is the output:
PyQt4.QtCore.QRect(100, 103, 20, 14)
PyQt4.QtCore.QRect(0, 0, 0, 0)
So it appears you will have to set the bounding rectangle yourself, though at least it is returned to you by the output of the drawText() method when passing in flags.
This does not seem like ideal behaviour, that you would have to set the bounding rectangle yourself. I hope someone else has the answer you're looking for, but I suspect you may want to report this bug.
Painting doesn't change the size of something in Qt. The main reason is this:
A component has to paint itself
The paint triggers a resize
The resize triggers painting -> endless loop
So the resize has to happen during the layout phase. After that, the bounds should not change.
To solve your problem, use QFontMetric to figure out how big your text is going to be during or close to the construction of your picture and then resize it accordingly.
[EDIT] Hm ... try to call end() before requesting the bounding rect. If that works, you've found a bug (can't see a reason why the bounding rect should not exist as you add elements...)

Resources