【发布时间】:2020-05-03 08:27:07
【问题描述】:
有什么方法可以可靠地让按钮的高度适合其内容?以前的一些答案建议使用布局和大小策略,或最大高度(How to make height of a QPushButton automatically fit the text?、Increase Height of QPushButton in PyQT、How can I set a QPushButton to grow vertically?),但它们似乎对我不起作用。
请参见下面的示例。这两个按钮是用它们默认的“一行”高度绘制的,所以里面的文本被剪掉了。将它们的大小策略设置为Preferred 或Minimum 不会改变任何东西。使用 addStretch 而不是 setAlignment 不会改变任何东西(使用 none 会使按钮拉伸以填充窗口,这不是我想要的)。更改最小高度是可行的,但这远非实际,除非有某种方法可以自动计算和设置它。
#!/usr/bin/env python3
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QSize
class HelloWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
button1 = QPushButton()
l = QVBoxLayout()
l.addWidget(QLabel('One'))
l.addWidget(QLabel('Description of button one'))
button1.setLayout(l)
#button1.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
#button1.setMinimumHeight(50)
button2 = QPushButton()
l = QVBoxLayout()
l.addWidget(QLabel('Two'))
l.addWidget(QLabel('Description of button two\nwith extra line'))
button2.setLayout(l)
#button2.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
#button2.setMinimumHeight(65)
layout = QVBoxLayout()
layout.addWidget(button1)
layout.addWidget(button2)
#layout.addStretch(1)
layout.setAlignment(QtCore.Qt.AlignTop)
centralWidget = QWidget(self)
centralWidget.setLayout(layout)
self.setCentralWidget(centralWidget)
self.resize(200, 400)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = HelloWindow()
mainWin.show()
sys.exit( app.exec_() )
【问题讨论】:
标签: qt user-interface pyqt5