1

I searched about but can't find a solution to align in center the text inside the QLineEdit

Example:

https://i.stack.imgur.com/eps2z.png

inosível
  • 21
  • 1
  • 1
  • 4

1 Answers1

6

alignment : Qt::Alignment

This property holds the alignment of the line edit

Both horizontal and vertical alignment is allowed here, Qt::AlignJustify will map to >Qt::AlignLeft.

By default, this property contains a combination of Qt::AlignLeft and Qt::AlignVCenter.

from PyQt5 import QtWidgets, QtCore

class Widget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.line_edit = QtWidgets.QLineEdit()
        self.line_edit.setAlignment(QtCore.Qt.AlignCenter)              # <-----
        self.line_edit.textChanged.connect(self.on_text_changed)

        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.line_edit)

        self.setLayout(layout)

    def on_text_changed(self, text):
        width = self.line_edit.fontMetrics().width(text)
        self.line_edit.setMinimumWidth(width)

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    mw = Widget()
    mw.show()
    app.exec()

enter image description here

Community
  • 1
  • 1
S. Nick
  • 12,879
  • 8
  • 25
  • 33