
Originally Posted by
d_stranz
Your example is a bit misleading because it shows only lowercase letters, and only letters with no ascenders (like "h") or descenders (like "g"). The vertical center is almost certainly calculated using the ascent and descent limits for the entire font, not just the text on display. Think about that - if only the actual text in the
QLineEdit was used to calculate vertical alignment, then the vertical location could jump up and down depending on what was on display. Probably not what you'd want.
Look at the
QFontMetrics, especially the
QFontMetrics::ascent() and
QFontMetrics::descent() values (or
QFontMetrics::height(), which is the sum of these). You will probably find that half the height corresponds to the center of your
QLineEdit, taking into account whatever margins or padding are used in the line edit.
Alternatively, it is possible that the vertical alignment is set to the font's baseline, which corresponds to
QFontMetrics::descent() above the bottom margin of the line edit. Either way, it will be fixed no matter what text is displayed.
I've attempted adding letters with ascenders, descenders, uppercase and zeroing out margins and padding, this was the code:
MainWindow::MainWindow(CoreDictionary const& dict)
{
ui.setupUi(this);
ui.searchField->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
ui.
searchField->setText
(QString("Type something here!"));
ui.searchField->setTextMargins(QMargins(0, 0, 0, 0));
ui.searchField->setStyleSheet("QLineEdit { padding: 0px 0px 0px 0px; }");
}
MainWindow::MainWindow(CoreDictionary const& dict)
: QMainWindow(nullptr), dict{dict}
{
ui.setupUi(this);
ui.searchField->setAlignment(Qt::AlignVCenter | Qt::AlignRight);
ui.searchField->setText(QString("Type something here!"));
ui.searchField->setTextMargins(QMargins(0, 0, 0, 0));
ui.searchField->setStyleSheet("QLineEdit { padding: 0px 0px 0px 0px; }");
}
To copy to clipboard, switch view to plain text mode
And this the result:
Immagine 1.png
Is that really Qt::AlignVCenter working as intended?
I've also tried changing the setTextMargin line with this:
ui.searchField->setTextMargins(QMargins(0, 0, 0, 6));
ui.searchField->setTextMargins(QMargins(0, 0, 0, 6));
To copy to clipboard, switch view to plain text mode
And this is the result:
Immagine 2.png
So by ignoring the setAlignment and raising the bottom margin instead I can get the text reasonably centered on the QLineEdit, the problem now is that the cursor (to the right of the exclamation mark) gets raised as well, so now that is not centered... I need help finding a solution :\
What I would like in the end is for the text and the cursor to be centered on the QLineEdit window
Bookmarks