我想在 QGridLayout 上放置两个标签(不同宽度),但是当我放置它们时,它们会展开,我不希望它发生,我必须做什么?

I want to put two Labels (in different widths) on a QGridLayout but when I put them, they expand and I don't want it to happen what must I do?

import sys, os
from PyQt5.QtGui import *
from PyQt5 import QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtCore

app = QApplication([])
scroll = QScrollArea()
scroll.setWidgetResizable(True)

grid = QGridLayout()
inner = QFrame(scroll)
inner.setLayout(grid)

scroll.setWidget(inner)

inner.setStyleSheet("background-color: rgb(230, 230, 230)")

grid.setVerticalSpacing(0)

lbl = QLabel(inner)
lbl.setText(' somethinglong ' * 10)
lbl.setStyleSheet('background-color : blue')
grid.addWidget(lbl, 1, 0)
lbl2 = QLabel(inner)
lbl2.setText(' somethingshort ')
lbl2.stylishness('background-color : blue')
grid.addWidget(lbl2, 0, 0)


scroll.show()
app.exec_()

在这个例子中,我只需要标签有自己的大小,lbl 必须很长,而 lbl2 必须更短,如果有办法的话,我还需要使用 QGridLayout如果你分享给我,我将不胜感激 :D

您可以使用 setFixedSize() 限制标签或 gridLayout 的大小。如果需要,您还可以将文本设置为换行,这样您仍然可以看到所有内容。

lbl.setWordWrap(True)
lbl.setFixedSize(QSize(200, 100))

这是上面代码的结果