Can't remove margins from QVBoxLayout

拥有回忆 提交于 2020-01-21 16:41:26

问题


I have set up an image button with some text, but the image does not align with the text due to some extra margins. How can I get rid of these margins? I have tried setting setContentsMargins(0,0,0,0) and setSpacing(0) on various components but it doesn't seem to affect the correct margins.

Here is a demo:

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_()

The Yellow region marks the text label, the Green region marks the imagebutton, and the Blue region marks the space I'm trying to get rid of. See how the yellow region expands to the size of the blue, with the end result that the text doesn't align to the imagebutton.

How can I get rid of this blue region?


回答1:


That margin is that of the QVBoxLayout that you use to place the QToolButton inside ImageButton, so the solution is to set it to 0 that margin:

# ...
class ImageButton(QWidget):
    def __init__(self, img_location):
        super().__init__(self)
        # ...
        layout = QVBoxLayout(self)
        layout.addWidget(self.button)
        layout.setContentsMargins(0, 0, 0, 0)
    # ...


来源:https://stackoverflow.com/questions/58885835/cant-remove-margins-from-qvboxlayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!