Getting QGraphicsTextItem length? - qt

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.

Related

Qt FontMetrics boundingrect vs Geometry rect

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;

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.

How to get the length of the left/right offsets in a QSlider?

I'm trying to make a subclass of QSlider that allows the user to insert "bookmarks" so they can remember significant locations on the slider. I've run into a problem painting the tabs on the slider - using QStyle.sliderPositionFromValue, I get a value but it is slightly inaccurate. If I'm on the left side of the slider, the tab is painted too far left, and on the right side it is painted too far right. I believe this is because QSlider.width() returns the width of the whole object, including the small offsets at the left and right. So width() might return 630 pixels, when the length of the slider itself is really 615.
This is the code I'm using to get the pixel position and draw a line across the slider.
pos = QStyle.sliderPositionFromValue(self.minimum(),self.maximum(),sliderIndex,self.width())
painter.drawLine(pos,0,pos,self.height())
I've been looking at the QT Source here starting on line 2699 and it seems like I need to be using the PixelMetric class from QStyle. I've tried using:
self.style().pixelMetric(QStyle.PM_SliderSpaceAvailable)
But that returns 0, which is clearly not the value I need.
I'd appreciate any advice.
Edit: As suggested in the comments, I changed the call to:
self.style().pixelMetric(QStyle.PM_SliderSpaceAvailable, QStyleOption(1,QStyleOption.SO_Slider),self)
This however, returns -14, which also doesn't match for the value of the offsets (I tried using self.width()-14 but the offset remains.

How to determine the number of charecter will fit to screen in Qt

How do I determine the number of characters in a particular font will fit to the screen?
Have a look at QFontMetrics. Using this, you can determine, among other things, the width of a particular string:
QFontMetrics metrics(myFont);
int width = metrics.width(myString);
Is this what you want?
Note: It is not possible to find the number of characters of a particular font that will fit on the screen since not all fonts are monospace. So the number of characters will depend on the actual characters.
you can also use QFontMetrics::elidedText passing available space (remember to reduce it with margins/paddings. Then call length on result string

MeasureString() pads the text on the left and the right

I'm using GDI+ in C++. (This issue might exist in C# too).
I notice that whenever I call Graphics::MeasureString() or Graphics::DrawString(), the string is padded with blank space on the left and right.
For example, if I am using a Courier font, (not italic!) and I measure "P" I get 90, but "PP" gives me 150. I would expect a monospace font to give exactly double the width for "PP".
My question is: is this intended or documented behaviour, and how do I disable this?
RectF Rect(0,0,32767,32767);
RectF Bounds1, Bounds2;
graphics->MeasureString(L"PP", 1, font, Rect, &Bounds1);
graphics->MeasureString(L"PP", 2, font, Rect, &Bounds2);
margin = Bounds1.Width * 2 - Bounds2.Width;
It's by design, that method doesn't use the actual glyphs to measure the width and so adds a little padding in the case of overhangs.
MSDN suggests using a different method if you need more accuracy:
To obtain metrics suitable for adjacent strings in layout (for example, when implementing formatted text), use the MeasureCharacterRanges method or one of the MeasureString methods that takes a StringFormat, and pass GenericTypographic. Also, ensure the TextRenderingHint for the Graphics is AntiAlias.
It's true that is by design, however the link on the accepted answer is actually not perfect. The issue is the use of floats in all those methods when what you really want to be using is pixels (ints).
The TextRenderer class is meant for this purpose and works with the true sizes. See this link from msdn for a walkthrough of using this.
Append StringFormat.GenericTypographic will fix your issue:
graphics->MeasureString(L"PP", 1, font, width, StringFormat.GenericTypographic);
Apply the same attribute to DrawString.
Sounds like it might also be connecting to hinting, based on this kb article, Why text appears different when drawn with GDIPlus versus GDI
TextRenderer was great for getting the size of the font. But in the drawing loop, using TextRenderer.DrawText was excruciatingly slow compared to graphics.DrawString().
Since the width of a string is the problem, your much better off using a combination of TextRenderer.MeasureText and graphics.DrawString..

Resources