简体   繁体   中英

Auto adjust size of QLabel according to text it contains

I have a QLabel and I would like to adjust the size of it, according to the text it contains (plus some margin on the sides)., I've tried this:

self.WarnLab = QtGui.QLabel(self.HeaderRight)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Avenir"))
font.setPointSize(18)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.WarnLab.setFont(font)
self.WarnLab.setObjectName("WarnLab")
r = self.WarnLab.fontMetrics().boundingRect(_translate("MainWindow","This is some, \nlonger multi-line text blahblahblah!",None))
self.WarnLab.fixedWidth(r.width())
self.WarnLab.fixedHeight(r.height())
self.WarnLab.setStyleSheet(_fromUtf8("QLabel { background-color : orange; color : white;}"))
self.gridLayout_2.addWidget(self.WarnLab, 0,0,0,0)

but QLabel doesn't have a property fixedWidth() , ie this won't work. Can anyone help me out?

If you need to set fixed dimensions in the widgets then you must use the setFixedWidth() , setFixedHeight() and/or setFixedSize() :

self.WarnLab.setFixedSize(r.size()) 

or

self.WarnLab.setFixedWidth(r.width())
self.WarnLab.setFixedHeight(r.height())

If you want to know all the methods of QLabel or any other widget you should check the docs of Qt, for example here is the docs of QLabel, and if you want all the methods you must click on the section "List of all members, including inherited members" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM