如何使Qlabel不填充BoxLayout

问题描述 投票:0回答:2

我有QWidget,它包含QVBoxLayout和QLabel。确实,当我将Qlabel放在QVBoxLayout中时,它会填充QVBoxLayout。如何使QLabel忽略QVBoxLayout。

enter image description here

如何仅在“文字标签”周围制作红色边框?

我尝试过使用setStyleSheet,setGeometry,但它没有用。我认为使用maximumsize并不是一个好选择。

谢谢

python pyqt qlabel
2个回答
0
投票

一个简单的解决方案是使用QSizePolicy,这样它就可以收缩到最小值而不是扩展:

from PyQt5 import QtCore, QtWidgets

class Label(QtWidgets.QLabel):
    def __init__(self, *args, **kwargs):
        super(Label, self).__init__(*args, **kwargs)
        self.setAlignment(QtCore.Qt.AlignCenter)
        self.setSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        lbl = Label("TextLabel")
        lbl.setStyleSheet('''background: red;''')
        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(lbl, alignment=QtCore.Qt.AlignCenter)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

enter image description here


1
投票

试试吧:

import sys
from PyQt5.QtWidgets import *

class Widget(QWidget):
    def __init__(self):
        super().__init__()

        label  = QLabel("TextLabel") 
        layout = QGridLayout(self)
        layout.addWidget(label)

CSS = """
QLabel {
    font-family: Ubuntu-Regular;
    font-size: 12px;
    qproperty-alignment: AlignCenter; 
    color: blue;
    border: 3px solid red;
    border-radius: 4px;
    min-height: 40px;
    max-height: 40px;
    min-width: 48px;
    max-width: 100px;
    background: yellow;    
}
"""        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyleSheet(CSS)
    ex = Widget()
    ex.show()
    app.exec_()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.