无法从QVBoxLayout中删除边距

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

我已经设置了带有一些文本的图像按钮,但是由于一些额外的空白,图像与文本不对齐。我如何摆脱这些利润?我尝试在各种组件上设置setContentsMargins(0,0,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,0,0)
layout_box.setSpacing(0)


layout_box.addWidget(imgbtn, 0, Qt.AlignTop)
layout_box.addWidget(label_title, 0, 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_()

“截图”

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

如何摆脱这个蓝色区域?

python python-3.x pyqt pyqt5 python-3.5
1个回答
0
投票

该边距是用于将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, 0, 0)
    # ...
© www.soinside.com 2019 - 2024. All rights reserved.