Search code examples
pythonpython-3.xpyqtpyqt5qlineedit

How to center text in a QLineEdit?


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

Example:

https://i.sstatic.net/eps2z.png


Solution

  • 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