简体   繁体   English

PyQt5:标签在网格布局中从顶部和底部截断

[英]PyQt5: Labels cut off top and bottom in grid layout

I am trying to add labels to a dialog window through a for loop.我正在尝试通过 for 循环向对话框 window 添加标签。 Optimally I would like for the row height to adjust to the content, so that if the string is one line, the row is one line high whereas if the string is 5 lines, the row reflects that.理想情况下,我希望行高可以根据内容进行调整,这样如果字符串是一行,则行高是一行,而如果字符串是 5 行,行会反映这一点。 This way I could add a scroll bar to go through all the content.这样我可以通过所有内容向 go 添加滚动条。

Instead I get this weird chop-off on the top and bottom of each label:相反,我在每个 label 的顶部和底部得到了这个奇怪的截断:

from PyQt5 import QtWidgets

app = QtWidgets.QApplication([])

window = QtWidgets.QDialog()
grid = QtWidgets.QGridLayout()
window.setLayout(grid)

window.setFixedWidth(200)
window.setFixedHeight(600)

for label in range(5):
    label = QtWidgets.QLabel()
    label.setText(2 * "This is a label with slightly too much text for this little window. Therefore it would be great to wrap this text and have the row size be adjusted automatically.")
    label.setWordWrap(True)
    grid.addWidget(label)

    label2 = QtWidgets.QLabel()
    label2.setText(2 * "HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA")
    label2.setWordWrap(True)
    grid.addWidget(label2)

window.show()
app.exec_()

Outcome when I run program我运行程序时的结果

Regarding comments about fixed width/height, this is the outcome with fixed width & height commented out:关于关于固定宽度/高度的注释,这是注释掉固定宽度和高度的结果:

Sounds like you want a QScrollArea:听起来你想要一个 QScrollArea:

from PyQt5 import QtWidgets

app = QtWidgets.QApplication([])

window = QtWidgets.QScrollArea(widgetResizable=True)
widget = QtWidgets.QWidget()
window.setWidget(widget)
grid = QtWidgets.QGridLayout(widget)

window.setFixedWidth(200)
window.setFixedHeight(600)

for label in range(5):
    label = QtWidgets.QLabel()
    label.setText(2 * "This is a label with slightly too much text for this little window. Therefore it would be great to wrap this text and have the row size be adjusted automatically.")
    label.setWordWrap(True)
    grid.addWidget(label)

    label2 = QtWidgets.QLabel()
    label2.setText(2 * "HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA HABALABOBA")
    label2.setWordWrap(True)
    grid.addWidget(label2)

window.show()
app.exec_()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM