I'm trying to set the width of a QScrollArea in PyQt5, but the only thing I found is setting the width through the
scroll.setFixedWidth(360)
function.
The issue is when I put the scroll bar area in a QSplitter
self.splitter2 = QSplitter(Qt.Horizontal)
self.splitter2.addWidget(scroll)
I cannot resize the scroll bar area width with the mouse any more.
What I would like to do is set the width of the scrollbar area (100 for instance) and be able to modify it afterwards when I click and drag the middle line of the QSplitter. For now it is one (set the width of the scrollbar area) or the other (modify the width with the mouse) - but not both at the same time.
Here's a minimal example:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class Viewer(QMainWindow):
def __init__(self, parent=None):
super(Viewer, self).__init__()
self.parent = parent
self.centralWidget= QWidget()
self.setCentralWidget(self.centralWidget)
self.mainHBOX = QHBoxLayout()
self.setFixedWidth(200)
self.setFixedHeight(200)
label1 = QLabel('blablabalblablabalblablabalblablabalblablabalblablabalblablabalblablabalblablabal')
label2 = QLabel('blablabal again')
scroll = QScrollArea()
scroll.setFixedWidth(100)
scroll.setWidget(label1)
scroll.setWidgetResizable(True)
self.splitter2 = QSplitter(Qt.Horizontal)
self.splitter2.addWidget(scroll)
self.splitter2.addWidget(label2)
self.mainHBOX.addWidget(self.splitter2)
self.centralWidget.setLayout(self.mainHBOX)
def main():
app = QApplication(sys.argv)
ex = Viewer(app)
ex.setWindowTitle('window')
# ex.showMaximized()
ex.show()
sys.exit(app.exec_( ))
if __name__ == '__main__':
main()
You should set the initial position of the splitter handle rather than setting the width of its child widgets. This can be done using QSplitter.setSizes:
leftwidth = 100
self.splitter2.setSizes([leftwidth, self.width() - leftwidth])
But note that the splitter won't allow moving its handle to a position less than the minimum width of a child widget. The default minimum width for a scroll-area is 100. So in the above example, setting leftwidth = 50
wouldn't work properly unless you explicitly reset the minimum width of the scroll-area accordingly.