Resizing a QLineEdit to contents



  • What's the right way to do this? adjustSize() doesn't seem to do anything and I've tried every combination of SizePolicies in my layout. Here are the specifics:

    • I've got an HBoxLayout.
    • Inside the layout I've got a QLineEdit and a spacer.
    • In code, I initialize the lineEdit with some text and call adjustSize().

    My goal is to size the lineedit to the text, but to resize no larger than my parent. adjustSize() doesn't appear to do this. Is there a trick to getting the layout to do this for me or do I have to resort to subclassing QLineEdit to provide a custom sizeHint?



  • I think you need override sizeHint() by subclassing QLineEdit.
    see the qt source(qlineedit.cpp)

    @
    .
    .
    /*!
    Returns a recommended size for the widget.

    The width returned, in pixels, is usually enough for about 15 to
    20 characters.
    

    */

    QSize QLineEdit::sizeHint() const
    {
    Q_D(const QLineEdit);
    ensurePolished();
    QFontMetrics fm(font());
    int h = qMax(fm.height(), 14) + 2d->verticalMargin
    + d->topTextMargin + d->bottomTextMargin
    + d->topmargin + d->bottommargin;
    int w = fm.width(QLatin1Char('x')) * 17 + 2
    d->horizontalMargin
    + d->leftTextMargin + d->rightTextMargin
    + d->leftmargin + d->rightmargin; // "some"
    QStyleOptionFrameV2 opt;
    initStyleOption(&opt);
    return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
    expandedTo(QApplication::globalStrut()), this));
    }

    /*!
    Returns a minimum size for the line edit.

    The width returned is enough for at least one character.
    

    */

    QSize QLineEdit::minimumSizeHint() const
    {
    Q_D(const QLineEdit);
    ensurePolished();
    QFontMetrics fm = fontMetrics();
    int h = fm.height() + qMax(2*d->verticalMargin, fm.leading())
    + d->topmargin + d->bottommargin;
    int w = fm.maxWidth() + d->leftmargin + d->rightmargin;
    QStyleOptionFrameV2 opt;
    initStyleOption(&opt);
    return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
    expandedTo(QApplication::globalStrut()), this));
    }
    .
    .
    @

    It seems that preffered/minimum sizes are not considering actual content.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.