无法从QVBoxLayout中删除边距

我设置了带有一些文本的图像按钮,但是由于一些额外的空白,图像与文本不对齐。我如何摆脱这些利润?我尝试在各种组件上设置setContentsMargins(0,0)setSpacing(0),但似乎不会影响正确的边距。

这是一个演示:

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class ImageButton(QWidget):
    def __init__(self,img_location):
        QWidget.__init__(self)
        self.img_location = img_location

        self.button = QToolButton(self)
        self.button.clicked.connect(self.handleButton)
        self.button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.button.setIcon(QIcon(img_location))
        self.button.setIconSize(QSize(300,400))
        layout = QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        print(self.img_location)


app = QApplication([])
window = QMainWindow()
window.resize(800,600)



label_title = QLabel("bob asdfjak f ajksf asljf ajdslf aldskj ksf kslfhadjks lfhiu sofhjaklfsiuod fahklfhadisufaksufhdsuifhosa fasdf afsda")
label_title.setStyleSheet('background-color: yellow')
label_title.setalignment(Qt.AlignCenter)
label_title.adjustSize()
label_title.setWordWrap(True)

imgbtn = ImageButton("a.png")
imgbtn.setStyleSheet('background-color: green')

layout_box = QVBoxLayout()
layout_box.setContentsMargins(0,0)
layout_box.setSpacing(0)


layout_box.addWidget(imgbtn,Qt.AlignTop)
layout_box.addWidget(label_title,Qt.AlignTop)
layout_box.setalignment(Qt.AlignCenter)
layout_box.setSpacing(0)

content = QWidget()
content.setStyleSheet('background-color: blue')
content.setfixedWidth(300)
content.setfixedHeight(400)
content.setLayout(layout_box)

window.setCentralWidget(content)
window.show()
app.exec_()

无法从QVBoxLayout中删除边距

黄色区域标记文本标签,绿色区域标记图像按钮,蓝色区域标记我要摆脱的空间。查看黄色区域如何扩展到蓝色的大小,最终结果是文本与图像按钮不对齐。

如何摆脱这个蓝色区域?

xiangxiangdetang 回答:无法从QVBoxLayout中删除边距

该裕度是用于将QToolButton放置在ImageButton内的QVBoxLayout的裕度,因此解决方案是将其设置为该裕度为0:

# ...
class ImageButton(QWidget):
    def __init__(self,img_location):
        super().__init__(self)
        # ...
        layout = QVBoxLayout(self)
        layout.addWidget(self.button)
        layout.setContentsMargins(0,0)
    # ...
本文链接:https://www.f2er.com/3092126.html

大家都在问