Reputation: 5492
I want a widget, which will be a horizontally scrollable text label, placed in the middle of a window (which is otherwise laid out via QGridLayout). With the code example below, I get this:
The image shows, that the label itself, allocated vertical space which is just enough for the two lines - which is what I want.
However, there is also extra vertical space, from the end (the bottom) of the label, to the start (the top) of the scrollbar.
Can I somehow get rid of this extra space, so the label keeps its current height, while it "sticks" to the scrollbar - and while still keeping the QGridLayout?
The code:
#!/usr/bin/python3
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.layout = QGridLayout()
self.layout.setRowStretch(0, 20)
self.layout.setRowStretch(1, 0)
self.layout.setRowStretch(2, 20)
self.scrollArea = QScrollArea(self)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.mylbl = QLabel("[]\n[]", self)
self.mylbl.setAlignment(Qt.AlignLeft | Qt.AlignTop)
self.mylbl.setStyleSheet("QLabel {background-color: gray;}")
self.mylbl.setTextInteractionFlags(Qt.TextSelectableByMouse)
self.mylbl.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.scrollArea.setWidget(self.mylbl)
self.scrollArea.setHorizontalScrollBarPolicy( Qt.ScrollBarAlwaysOn )
self.layout.addWidget(self.scrollArea, *(1,0), *(1,2))
self.setLayout(self.layout)
self.setGeometry(300, 300, 220, 170)
self.setWindowTitle('Tester')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Upvotes: 0
Views: 685
Reputation: 48424
If you are sure that the label will always have the same height, you can set a fixed height to the scrollarea:
# get the size hint of the label
height = self.mylbl.sizeHint().height()
# add the scrollbar height
height += self.scrollArea.horizontalScrollBar().sizeHint().height()
# add the scrollarea frame size * 2 (top and bottom)
height += self.scrollArea.frameWidth() * 2
self.scrollArea.setFixedHeight(height)
Upvotes: 3