答案 0 :(得分:0)
alignment:Qt :: Alignment
此属性保存行编辑的对齐方式
此处允许水平和垂直对齐,Qt :: AlignJustify将映射到> Qt :: AlignLeft。
默认情况下,此属性包含Qt :: AlignLeft和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()