[Qt-interest] Calculating text size in QLineEdit
Andre Somers
andre at familiesomers.nl
Tue Mar 8 11:23:32 CET 2011
Hi,
Op Di, 8 maart, 2011 11:10 am, schreef Matthias Paul:
>
> -------- Original-Nachricht --------
>> Datum: Tue, 8 Mar 2011 10:20:23 +0100
>> Von: "Andre Somers" <andre at familiesomers.nl>
>> An: "\'qt-interest at trolltech.com\'" <qt-interest at trolltech.com>
>> Betreff: Re: [Qt-interest] Calculating text size in QLineEdit
>
>> Op Di, 8 maart, 2011 10:06 am, schreef Matthias Paul:
>> > Hello!
>> >
>> > I created a QLineEdit subclass, which automatically displays a
>> truncated
>> > text if the original text is too long for the widget's size, so that
>> > there's no need to scroll for the user. Instead a tooltip with full
>> text
>> > is displayed.
>> >
>> > QFontMetrics calculates the size required for the displayed text based
>> on
>> > QWidget's size() (provided by ResizeEvent). Still, I cannot figure out
>> how
>> > to get the the text label size _minus_ widget's borders and margins.
>> Guess
>> > I have to use QStyle somehow, so can someone give me a hint please?
>>
>> Perhaps you can use QStyle::subElementRect, using
>> QStyle::SE_LineEditContents for the element argument, and a style option
>> initialized with your line edit widget as the style option? That should
>> give you the rect that is available to draw the text.
>>
>> André
>>
>
> Hello André!
>
> Thank you for your reply!
>
> The subelementRect() always returns an invalid QRect, although the
> QLineEdit is displayed and has content in it.
>
> That's what I tried: (typos included)
> --------------------------------------------------
> void
> TruncatedLineEdit::resizeEvent(
> QResizeEvent * resizeEvent) {
>
> QLineEdit::resizeEvent(resizeEvent);
>
> qDebug() << "QWidget's size (by event):" << resizeEvent->size();
> QStyleOption option;
> option.initFrom(this);
> qDebug() << "QWidget's content rect (by style):"
> << this->style()->subElementRect(
> QStyle::SE_LineEditContents,
> &option,
> this);
> // do smth with size information
> }
> --------------------------------------------------
>
> The output is:
> --------------------------------------------------
> QWidget's size (by event): QSize(246, 22)
> QWidget's content rect (by style): QRect(0,0 0x0)
> --------------------------------------------------
>
>
> Is it because QLineEdit has no user-style set to it? QLineEdit has been
> set with usual calls like setFont(), setReadOnly() and setObjectName().
I would have expected your code to work. I don't know why it doesn't.
Sorry! Perhaps you can check QLineEdit's sources to find out how QLineEdit
itself determines the rect to draw the text in?
André
More information about the Qt-interest-old
mailing list