Set minimal reasonable width for a QScrollArea - python

I am relatively new to Qt, which I access through PySide.
I have a longish list of content that I want to make vertically scrollable.
The horizontal size is not an issue. I tried using QScrollArea for that. Here is a minimal example:
import sys
import PySide.QtGui as gui
application = gui.QApplication(sys.argv)
window = gui.QScrollArea()
list = gui.QWidget()
layout = gui.QVBoxLayout(list)
for i in range(100):
layout.addWidget(gui.QLabel(
"A something longish, slightly convoluted example text."))
window.setWidget(list)
window.show()
sys.exit(application.exec_())
What happens:
The scroll-area sets its horizontal size to the size needed for the labels
It notices that the vertical space is insufficient, so it adds a vertical scrollbar.
Due to the vertical scrollbar, the horizontal space is now insufficient as well, and so the horizontal scrollbar is also shown.
I can make the horizontal scrollbar go away with setHorizontalScrollBarPolicy, but the main problem persists: the vertical scrollbar obscures part of the labels.
How can I set the width of the scroll-area to the minimal value which does not need a horizontal scrollbar?

Your example is somewhat unrealistic, because the scroll-area is made the top-level window. More typically, it would be a child widget, and its initial size would be determined by a layout, and would be indirectly constrained by the sizes of other widgets and/or layouts. As a top-level window, the constraints are different, and partly under the influence of the window-manager (the exact behaviour of which can vary between platforms).
To ensure that the scroll-area has the correct size, you must set a minimum width for it, based on its contents, and also allowing for the vertical scrollbar and the frame. It is also probably best to set the widgetResizable property to True and add an expandable spacer to the end of the contents layout.
In the example below, I have changed the background colour of the labels to make it easier to see what is going on. I have also allowed resizing the window smaller than its initial size, by resetting the minimum width after it is shown - but that is optional.
import sys
import PySide.QtGui as gui
application = gui.QApplication(sys.argv)
window = gui.QScrollArea()
window.setWidgetResizable(True)
list = gui.QWidget()
layout = gui.QVBoxLayout(list)
# just for testing
window.setStyleSheet('QLabel {background-color: red}')
for i in range(30):
layout.addWidget(gui.QLabel(
"A something longish, slightly convoluted example text."))
layout.addStretch()
window.setWidget(list)
window.setMinimumWidth(
list.sizeHint().width() +
2 * window.frameWidth() +
window.verticalScrollBar().sizeHint().width())
window.show()
# allow resizing smaller
window.setMinimumWidth(1)
sys.exit(application.exec_())

Try to use sizeHint() in the widgets and use the result to set the minimum width of the QScrollArea.
Some extra info here: http://doc.qt.io/qt-5/layout.html

Related

Remove empty space at bottom of QTableWidget

I'm using PySide6 6.4.1 to build a table widget that automatically resizes to the number of rows. Here's a minimal example:
from PySide6.QtWidgets import *
class MW(QWidget):
def __init__(self):
super().__init__()
self.button = QPushButton("Test")
self.table = QTableWidget(self)
self.table.setColumnCount(1)
self.table.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
self.setLayout(QVBoxLayout(self))
self.layout().addWidget(self.button)
self.layout().addWidget(self.table)
self.button.clicked.connect(self.test)
return
def test(self):
self.table.insertRow(0)
self.table.setItem(0, 0, QTableWidgetItem("new item"))
self.table.adjustSize()
self.adjustSize()
return
app = QApplication()
mw = MW()
mw.show()
app.exec()
Somehow this always leaves a bit of empty space at the bottom of the table. How do I get rid of this space without doing manual resizing?
(Nevermind the weird font size, it's a known bug when using UI scaling. I've adjusted the font size manually as well and it doesn't get rid of this problem.)
Qt item views inherit from QAbstractScrollArea, which has some peculiar size related aspects:
it has an Expanding size policy that tells the parent layout it can use as much space as possible, possibly increasing the available space at initialization;
it has a minimumSizeHint() that always includes a minimum reasonable size allowing showing the scroll bars (even if they are not visible);
if the sizeAdjustPolicy is AdjustToContents it's also based on the viewport size hint;
It's also mandatory to consider a fundamental aspect about scroll areas: size management is a tricky subject, and some level of compromise is necessary most of the times. This is the case whenever the scroll bars potentially change the available size of the viewport (the part of the widget that is able to scroll), which is the default behavior of Qt in most systems, unless the scroll bars are always hidden/visible or they are transient (they "overlay" above the viewport without affecting its available visible size).
To clarify this aspect, consider a scroll area with content that has a minimum size of 100x100 and scroll bars that have a default extent (width for the vertical one, height for the horizontal) of 20: if the height hint of the content is changed to 110, then you'd theoretically need an area of 100x110. But Qt needs to know the hints before laying out widgets and setting their geometries. This means that you cannot know if the scroll bars have to be shown before the widget is finally laid out, but that hint is required to lay out the widget itself. So, recursion.
Qt layout management is a system that is far from perfect, but I doubt that there is one, at least considering normal UI management (don't consider web layouts: their concept is based on different assumption, most importantly the fact that the whole "window" has potentially infinite dimensions). This is an aspect that must be always considered, especially if the shown contents are set to adapt their size based on the contents; it's the case of fitInView() of QGraphicsView or the known issues of QLayout with rich text based widgets.
Qt doesn't provide "foolproof" solutions for these aspects, because its layout management doesn't allow it as it has been implemented primarily considering performance and usability: the UI has to work and be responsive before being "fancy".
It's one of the reasons for which it's almost impossible to have real fixed-aspect-ratio widgets or windows. You can work around it, but at some point you'll have some inconsistencies, and you have to live with that. Also consider that this kind of behavior is generally not very UX-friendly. UI elements that resize themselves (and, consequentially, alter the whole layout) at anytime are usually annoying and very user-unfriendly, especially if they displace their or other contents: it's like having a car that constantly moves the driving controls depending on the amount of passengers.
That said, it's not impossible to have a partially working solution.
The requirements are to:
override minimumSizeHint(), so that a minimal reasonable size is always returned;
override sizeHint() that is used to adjust the widget (and parents) based on the contents of the view;
change the vertical size policy of the table to Preferred, which will tell the layout manager that the height of the size hint will be considered as default, still allowing it to expand in case other items in the layout don't use the remaining space, and eventually shrink it if required;
eventually do the same for the horizontal policy in order to adapt it to the actual horizontal header size, otherwise use self.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch), but be aware that this might complicate things (see the note after the code);
class TableWidget(QTableWidget):
def sizeHint(self):
hHeader = self.horizontalHeader()
vHeader = self.verticalHeader()
f = self.frameWidth() * 2
# the simple solution is to get the length, but this might be a problem
# whenever *any* section of the header is set to Stretch
targetWidth = width = f + hHeader.length()
# a possible alternative (but still far from perfect):
width = f
for c in range(self.columnCount()):
if hHeader.isSectionHidden(c):
continue
width += self.sizeHintForColumn(c)
targetWidth = width
if not vHeader.isHidden():
width += vHeader.width()
hpol = self.horizontalScrollBarPolicy()
height = f + vHeader.length() + hHeader.height()
if (
hpol != Qt.ScrollBarAlwaysOff
and not self.horizontalScrollBar().isHidden()
and (
hpol == Qt.ScrollBarAlwaysOn
and hHeader.length() + f < targetWidth
)
):
height += self.horizontalScrollBar().sizeHint().height()
return QSize(width, height)
def minimumSizeHint(self):
hint = self.sizeHint()
minHint = super().minimumSizeHint()
return QSize(
min(minHint.width(), hint.width()),
min(super().minimumSizeHint().height(), hint.height())
)
class MW(QWidget):
def __init__(self):
# ...
pol = self.table.sizePolicy()
pol.setVerticalPolicy(QSizePolicy.Preferred)
self.table.setSizePolicy(pol)
Be aware that the above doesn't solve all problems. It might work fine for a QTableView having just one column or when using the default interactive (or fixed) section resize mode, but whenever you set different resize modes for each column the result may be wrong.
In order to provide a finer resize, you'll need to do much complex computations that take into account each section resize mode for the horizontal header, the default/minimum/maximum and eventually the hint based on the content.
Further notes: 1. calling adjustSize() on the parent is normally enough, it's not necessary to do it on the children; 2. self.setLayout(QVBoxLayout(self)) is pointless, the self argument already sets the layout; just use layout = QVBoxLayout(self) and use that as a local variable to add widgets; 3. in Python the return at the end of a function is always implicit, you shall not add it as it's useless, redundant and distracting.

Tkinter window resize to fit content without touching

I have created an application that required to use the place() manager. I tried using pack() and grid() but after many tries and lots of effort it did not work for my goals. Since I use relx= and rely= almost all the time and I want to put my app on multiple OS's I need to have the window resize to fit all the widgets without them touching.
Is there a way to do this? Since many OS's and their updates change rendering the sizes of widgets changes greatly and I don't want the user to have to resize the window all the time. I want it to just fit as tightly as possible or get the minimum width and height to I can add some buffers. Is this possible? If not, is there a way to fix my app without having to rewrite everything?
Note:
I found something similar: Get tkinter widget size in pixels, but I couldn't properly get it to work.
I figured it out. You can use the widget.winfo_height()/widget.winfo_width() functions to get the minimum pixel sizes. Since the window.geometry() function requires pixel sizes you can make two lists: one for width, and one for height. By adding the minimum amount of widgets you can get the desired size.
Code:
height_widget_list = [main_label, main_notebook, the_terminal, quit_button, settings_button]
width_height_list = [commands_label, main_notebook, quit_button]
widget_list = [main_label, main_notebook, the_terminal, quit_button, settings_button, commands_label]
# Widgets must be updated for height and width to be taken
for widget in widget_list:
widget.update()
height_required_list = []
width_required_list = []
# Collects data
for widget in height_widget_list:
height_required_list.append(int(widget.winfo_height()))
for widget in width_height_list:
width_required_list.append(int(widget.winfo_width()))
# Get height requirement
minimum_height = 0
for height in height_required_list:
minimum_height += height
# Get width requirement
minimum_width = 0
for width in width_required_list:
minimum_width += width
# Make window correct size make window require the correct sizing
window.geometry("{}x{}".format(minimum_width, minimum_height))
window.resizable(False, False)

Stacked Layout causing alignment to top problem

I have a vertical layout with alignment set to "top" that contains what I want to be a fixed height "header" bar contained in a QHBoxLayout, with a QTextEdit window underneath it. One of the sections of this header bar contains a QStackedLayout. If you run the sample code below, when resizing the window the QTextEdit window begins pulling away from the "header" bar instead of staying anchored just underneath the "header" bar. The intended behavior would be for the QTextEdit window to remain anchored just underneath the header bar and expand and contract along its bottom margin. How do I fix the size of the QStackedLayout element to achieve this behavior?
from PySide2 import QtWidgets, QtCore, QtGui
from PySide2.QtWidgets import QApplication
import sys
class Demo(QtWidgets.QDialog):
def __init__(self, parent=None):
super(Demo, self).__init__(parent)
self.main_layout = QtWidgets.QVBoxLayout(self)
self.main_layout.setAlignment(QtCore.Qt.AlignTop)
# Header with combobox anchored to the top of the layout
self.data_results_layout = QtWidgets.QHBoxLayout()
self.results_stacked_layout = QtWidgets.QStackedLayout()
self.data_results_layout.addLayout(self.results_stacked_layout)
self.combobox_results_widget = QtWidgets.QWidget()
self.combobox_results_widget.setFixedHeight(25)
self.combobox_results_layout = QtWidgets.QVBoxLayout(self.combobox_results_widget)
self.combobox_results_layout.setContentsMargins(0,0,0,0)
self.directory_combobox = QtWidgets.QComboBox()
self.directory_combobox.setFixedHeight(25)
self.combobox_results_layout.addWidget(self.directory_combobox)
self.results_stacked_layout.addWidget(self.combobox_results_widget)
self.main_layout.addLayout(self.data_results_layout)
# QTextEdit Window
self.asset_data_layout = QtWidgets.QVBoxLayout()
self.asset_data_window = QtWidgets.QTextEdit('Ready.')
self.asset_data_layout.addWidget(self.asset_data_window)
self.main_layout.addLayout(self.asset_data_layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = Demo()
demo.show()
sys.exit(app.exec_())
Setting the alignment on a layout does not set the alignment of the widgets it manages, but only the alignment that that layout will have when added to another layout manager (you can read a more deeper explanation in this answer).
Basically, the following:
layout.setAlignment(QtCore.Qt.AlignTop)
is almost the same as this:
otherLayout.addLayout(layout, alignment=QtCore.Qt.AlignTop)
So, not only that alignment won't affect the children alignment, but since you're using that layout as main layout for the widget, that alignment is completely ignored.
In order to achieve what you want you can set a stretch for the lower alignment (as suggested in the comment by S.Nick):
self.main_layout.addLayout(self.asset_data_layout, stretch=1)
On the other hand, consider that QStackedLayout should only used for custom widgets or dedicated behavior, and in most cases it's better to use its convenience class QStackedWidget, on which you can set an appropriate size policy:
self.results_stacked_layout = QtWidgets.QStackedWidget()
self.data_results_layout.addWidget(self.results_stacked_layout)
self.results_stacked_layout.setSizePolicy(
QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Maximum)
With the above, the stacked widget will resize itself horizontally according to its contents and will only use the minimum vertical space required by it: since the combobox expands horizontally as much as possible, it will try to occupy all the horizontal available space, and since the vertical policy of the combobox is fixed, it will only use the vertical space required, leaving all the remaining vertical space to the other widgets in the parent layout.
Note that the size policy definitions might seem a bit counterintuitive; the rule is that it's always referred to the sizeHint of the widget: Maximum means that the size hint of the contents will be used as maximum size, and it cannot be larger than that.

How to add an invisible line in PyQt5

This attached image is the screenshot of an application developed using PyQt5.
The image clearly has an invisible line running in the middle of the boxes enclosing the contents.
What code should I add in my program to draw an invisible line overlaying all other objects created earlier. I couldn't find any documentation regarding this but as the image suggests, it has somehow been implemented.
A code snippet is not needed to be provided by me since this is a question about adding/developing a feature rather than debugging or changing any existing code.
Premise: what you provided as an example doesn't seem a very good thing to do. It also seems more a glich than a "feature", and adding "invisible" lines like that might result in an annoying GUI for the user. The only scenario in which I'd use it would be a purely graphical/fancy one, for which you actually want to create a "glitch" for some reason. Also, note that the following solutions are not easy, and their usage requires you an advanced skill level and experience with Qt, because if you don't really understand what's happening, you'll most certainly encounter bugs or unexpected results that will be very difficult to fix.
Now. You can't actually "paint an invisible line", but there are certain work arounds that can get you a similar result, depending on the situation.
The main problem is that painting (at least on Qt) happens from the "bottom" of each widget, and each child widget is painted over the previous painting process, in reverse stacking order: if you have widgets that overlap, the topmost one will paint over the other. This is more clear if you have a container widget (such as a QFrame or a QGroupBox) with a background color and its children use another one: the background of the children will be painted over the parent's.
The (theoretically) most simple solution is to have a child widget that is not added to the main widget layout manager.
Two important notes:
The following will only work if applied to the topmost widget on which the "invisible line" must be applied.
If the widget on which you apply this is not the top level window, the line will probably not be really invisible.
class TestWithChildLine(QtWidgets.QWidget):
def __init__(self):
super().__init__()
layout = QtWidgets.QGridLayout(self)
for row in range(3):
for col in range(6):
layout.addWidget(QtWidgets.QDial(), row, col)
# create a widget child of this one, but *do not add* it to the layout
self.invisibleWidget = QtWidgets.QWidget(self)
# ensure that the widget background is painted
self.invisibleWidget.setAutoFillBackground(True)
# and that it doesn't receive mouse events
self.invisibleWidget.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
def resizeEvent(self, event):
super().resizeEvent(event)
# create a rectangle that will be used for the "invisible" line, wide
# as the main widget but with 10 pixel height, then center it
rect = QtCore.QRect(0, 0, self.width(), 10)
rect.moveCenter(self.rect().center())
# set the geometry of the "invisible" widget to that rectangle
self.invisibleWidget.setGeometry(rect)
Unfortunately, this approach has a big issue: if the background color has an alpha component or uses a pixmap (like many styles do, and you have NO control nor access to it), the result will not be an invisible line.
Here is a screenshot taken using the "Oxygen" style (I set a 20 pixel spacing for the layout); as you can see, the Oxygen style draws a custom gradient for window backgrounds, which will result in a "not invisible line":
The only easy workaround for that is to set the background using stylesheets (changing the palette is not enough, as the style will still use its own way of painting using a gradient derived from the QPalette.Window role):
self.invisibleWidget = QtWidgets.QWidget(self)
self.invisibleWidget.setObjectName('InvisibleLine')
self.invisibleWidget.setAutoFillBackground(True)
self.invisibleWidget.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
self.setStyleSheet('''
TestWithChildFull, #InvisibleLine {
background: lightGray;
}
''')
The selectors are required to avoid stylesheet propagation to child widgets; I used the '#' selector to identify the object name of the "invisible" widget.
As you can see, now we've lost the gradient, but the result works as expected:
Now. There's another, more complicated solution, but that should work with any situation, assuming that you're still using it on a top level window.
This approach still uses the child widget technique, but uses QWidget.render() to paint the current background of the top level window on a QPixmap, and then set that pixmap to the child widget (which now is a QLabel).
The trick is to use the DrawWindowBackground render flag, which allows us to paint the widget without any children. Note that in this case I used a black background, which shows a "lighter" gradient on the borders that better demonstrate the effect:
class TestWithChildLabel(QtWidgets.QWidget):
def __init__(self):
super().__init__()
layout = QtWidgets.QGridLayout(self)
layout.setSpacing(40)
for row in range(3):
for col in range(6):
layout.addWidget(QtWidgets.QDial(), row, col)
self.invisibleWidget = QtWidgets.QLabel(self)
self.invisibleWidget.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
palette = self.palette()
palette.setColor(palette.Window, QtGui.QColor('black'))
self.setPalette(palette)
def resizeEvent(self, event):
super().resizeEvent(event)
pm = QtGui.QPixmap(self.size())
pm.fill(QtCore.Qt.transparent)
qp = QtGui.QPainter(pm)
maskRect = QtCore.QRect(0, 0, self.width(), 50)
maskRect.moveTop(50)
region = QtGui.QRegion(maskRect)
self.render(qp, maskRect.topLeft(), flags=self.DrawWindowBackground,
sourceRegion=region)
qp.end()
self.invisibleWidget.setPixmap(pm)
self.invisibleWidget.setGeometry(self.rect())
And here is the result:
Finally, an further alternative would be to manually apply a mask to each child widget, according to their position. But that could become really difficult (and possibly hard to manage/debug) if you have complex layouts or a high child count, since you'd need to set (or unset) the mask for all direct children each time a resize event occurs. I won't demonstrate this scenario, as I believe it's too complex and unnecessary.

PyQt4: set size of QGridLayout depending on size of QMainWindow

I'm writing a little Qt application with Python. I've created QMainWindow, which have a QGridLayout. In each grid I'm adding QTextBrowser Widget. I want left side of my grid to be not bigger than 25% of window. So I'll have two QTextBrowsers: one is 25% of window's width, and another is 75% of window's width. How can I do it? Thanks!
You can specify relative width by giving each cell a stretch with setStretch(). They will get sizes proportional to the given stretches. Here is a simple example that makes the right widget 3 times greater than the left widget.
import sys
from PyQt4 import QtGui
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
Q = QtGui.QWidget()
H = QtGui.QHBoxLayout()
H.addWidget(QtGui.QTextBrowser())
H.setStretch(0,1)
H.addWidget(QtGui.QTextBrowser())
H.setStretch(1,3)
Q.setLayout(H)
Q.show()
app.exec_()
But, bear in mind that widgets have minimum sizes by default. So they can shrink below that. If you want to change that behavior also, consider setting minimum sizes to your liking.

Categories