Issue
I am working with PyQt5 and would like to stack some controls on top of each other. I want these controls to be able to determine their own size based upon their contents. For example, if I had three buttons with the content "one", "two two", and "three three three", the first button should be the smallest, and in the top left, the second should be immediately under the first and slightly wider, and so on. It should be mentioned that these will be placed in a QScrollArea
, you can expect hundreds of stacked items.
I have tried a QVBoxLayout
, but the buttons all receive the same size, stretch across the screen, and float in the middle if there isn't enough to fill up the parent.
Solution
You can set the alignment of the widgets in QVboxLayout
to stop them streching to fit the width. And you can also add a stretchable spacer to the end of the layout to stop the widgets spacing themselves out vertically.
When put inside a scroll-area, it will then look like this:
Here's a simple demo:
import sys
from PyQt5 import QtCore, QtWidgets
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
scroll = QtWidgets.QScrollArea()
widget = QtWidgets.QWidget(scroll)
vbox = QtWidgets.QVBoxLayout(widget)
for index in range(5):
for text in 'One', 'Two Two', 'Three Three Three':
button = QtWidgets.QToolButton()
button.setText('%s %s' % (text, index))
vbox.addWidget(button, 0, QtCore.Qt.AlignLeft)
vbox.addStretch()
scroll.setWidget(widget)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(scroll)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 300, 300)
window.show()
sys.exit(app.exec_())
Answered By - ekhumoro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.