【发布时间】:2020-03-12 03:02:46
【问题描述】:
我设置了一个带有一些文本的图像按钮,但由于一些额外的边距,图像与文本不对齐。我怎样才能摆脱这些利润?我尝试在各种组件上设置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