如何在 QLineEdit 中居中文本?

How to center text in a QLineEdit?

我搜索了但找不到解决方案来将 QLineEdit 中的文本居中对齐

示例:

https://i.imgur.com/XmmxqSf.png

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()