简体   繁体   中英

PyQt5: Labels cut off top and bottom in grid layout

I am trying to add labels to a dialog window through a for loop. 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. This way I could add a scroll bar to go through all the content.

Instead I get this weird chop-off on the top and bottom of each 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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