How to write QGraphicsTextItem from it's end ?
-
I have a QGraphicsItem. I want to do naming inside QGraphicsItem.
Currently naming looks like below image.

I want text "parallel out" should be written like "rx_frame" i.e. it should start from small rectangle ( i.e. pin )
If I try to adjust "x axis" of parallel out" text then, text "rx_frame" goes outside outer rectangle.
I tried this way :class myText : public QGraphicsTextItemmyText* text = new myText(pinName.str().c_str()) // here "rx_frame" or "parallel out" gets pass. QFont font; QFontMetrics fontMetrics(font); QFont font1 = text->font(); font1.setPixelSize(5); text->setFont(font1); QRect rect = fontMetrics.boundingRect(pinName.str().c_str()); int width = rect.width(); text->DrawText(_firstPos - width + 45, _secondPos + 10);void myText::DrawText(int firstPos, int secondPos) { this->setPos(firstPos, secondPos); } -
It seems strange that you derive from QGraphicsTextItem, then write code to draw the text.
Also, do you need the capabilities of QGraphicsTextItem, or would QGraphicsSimpleTextItem be sufficient?In both cases: When you assign the text, the item will automatically adjust it's bounding Rect. The position of the item would in this case be the top-left corner. So the task is to set the item position in such a way that it will be just where you want it.
Assuming you use a plain QGraphicsText or QGraphicsSimpleText, let's see what happens:
When you set the text, this will trigger a change of the boundingRect. Using position and boundingRect together, you could easily set the correct position. Unfortunately, there is no way for you to know when the boundingRect changes, so you cannot rely on that.Depending on your needs and how narrow your requirements are, you have multiple options
- Updating the position asynchronously after setting the text should work, but may flicker
- Calculating the expected width yourself using QFontMetricsF should get close (for single-line texts), but may be a few pixels off
For a complete solution, I found no other way to completely re-write QGraphicsSimpleText, using QTextLayout internally for multi-line text. Then, you have full control of item size, and can also implement a text alignment property.