QT pyqt pyside2 QLabel 自动换行设置注意点
先看效果:
PySide2(QT5) 的 QT Designer (我在 QT4 的 designer 中不可以直接看效果,可能需要设置什么)能直接在编辑器中看效果,Label设置如下:
注意:不要在同HorizonLayout中加弹簧,Label Horizontal 必须是 Expanding 的,很长的英文单词并不会像中文那样会分开换行,所以注意英文单词之间要用空格键隔开。
代码:
1 # -*- coding: utf-8 -*- 2 3 # Form implementation generated from reading ui file '.\labelAutoMultiLine.ui' 4 # 5 # Created: Fri Nov 02 19:02:05 2018 6 # by: pyside-uic 0.2.15 running on PySide 1.2.4 7 # 8 # WARNING! All changes made in this file will be lost! 9 10 from PySide import QtCore, QtGui11 12 class Ui_Form(object):13 def setupUi(self, Form):14 Form.setObjectName("Form")15 Form.resize(315, 86)16 self.horizontalLayout = QtGui.QHBoxLayout(Form)17 self.horizontalLayout.setObjectName("horizontalLayout")18 self.pushButton = QtGui.QPushButton(Form)19 sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)20 sizePolicy.setHorizontalStretch(0)21 sizePolicy.setVerticalStretch(0)22 sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())23 self.pushButton.setSizePolicy(sizePolicy)24 self.pushButton.setMinimumSize(QtCore.QSize(64, 64))25 self.pushButton.setMaximumSize(QtCore.QSize(64, 64))26 self.pushButton.setObjectName("pushButton")27 self.horizontalLayout.addWidget(self.pushButton)28 self.label = QtGui.QLabel(Form)29 sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred)30 sizePolicy.setHorizontalStretch(0)31 sizePolicy.setVerticalStretch(0)32 sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())33 self.label.setSizePolicy(sizePolicy)34 self.label.setWordWrap(True)35 self.label.setObjectName("label")36 self.horizontalLayout.addWidget(self.label)37 38 self.retranslateUi(Form)39 QtCore.QMetaObject.connectSlotsByName(Form)40 41 def retranslateUi(self, Form):42 Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))43 self.pushButton.setText(QtGui.QApplication.translate("Form", "Button", None, QtGui.QApplication.UnicodeUTF8))44 self.label.setText(QtGui.QApplication.translate("Form", "TextLabel", None, QtGui.QApplication.UnicodeUTF8))
1 # -*- coding: utf-8 -*- 2 import sys 3 from PySide import QtCore, QtGui 4 import labelAutoMultiLine_ui_pyside as ui 5 6 class TestWindow(QtGui.QWidget, ui.Ui_Form): 7 def __init__(self, parent = None): 8 super(TestWindow, self).__init__(parent) 9 self.setupUi(self)10 11 self.label.setWordWrap(True) #也可以在qt designer中对label的属性设置12 self.label.setText(u'测试Label自动换行,SDFSDF SFSDF 啊啊啊啊啊啊') # 如果在designer中设置好很长的text,在代码中不设置,则可能不会自动换行13 14 def main():15 app = QtGui.QApplication(sys.argv)16 win = TestWindow()17 win.show()18 sys.exit(app.exec_())19 20 if __name__ == '__main__':21 main()