3

I have a similar issue as in this question, but the answer to that does not work well for me.

I have a QLineEdit element with a short piece of text, and I want this element to be adjusted in width to the contents, so that the text fits right into the element, without extra spaces or hidden letters. I use QFontMetrics for that, but the result is as if there is a bit of shift, so that leftmost letter is partially hidden, while there is a bit of space on the right:

QLineEdit too short

My code is the following:

#include <QtWidgets>

int main ( int argc, char** argv) {
   QApplication app (argc, argv);
   QLineEdit *lineEdit = new QLineEdit;

   QString text = "Hello, world!";
   lineEdit->setText(text);
   QFontMetrics fm = lineEdit->fontMetrics();
   int w = fm.boundingRect(text).width();
   // int w = fm.width(text);
   lineEdit->setFixedWidth(w);
   lineEdit->show();

   return app.exec();
}

Playing with setAlignment made no any difference.

Maximko
  • 627
  • 8
  • 20

1 Answers1

2

QFontMetrics doesn't take into account the style-dependent frame of the widget (here the parts that provide the 3D effect) which add to its total size. For a general solution you'll have to dig into QStyle::PixelMetric and query the additional margins for the frame, depending on the widget type. Note that sometimes you've got to double the values, for left and right/top and bottom frame.

An easy solution, but not portable over styles (and thus not platform independent) is to find by trial&error a constant margin for the style used, and add this to the width. Example:

lineEdit->setFixedWidth(fm.boundingRect(text).width() + 6);
Murphy
  • 3,827
  • 4
  • 21
  • 35