I'm trying to create a wx.StaticBox having a constant size, regardless to the size of the widget within. So I have a panel containing the following code:
box = wx.StaticBox(self, -1, 'BoxTitle', size=(200, 200))
bsizer = wx.StaticBoxSizer(box, wx.VERTICAL)
text = wx.StaticText(self, -1, 'Text')
bsizer.Add(text)
border = wx.BoxSizer()
border.Add(bsizer)
self.SetSizer(border)
However, the box simply wraps the StaticText widget within, instead of sticking to the specified 200x200 size. How do I make the box conform to a hard-coded size?
If you add the following after creating your StaticBox it will force the size for you:
box.SetMaxSize((200,200))
Note that a StaticText box does not wrap its text, so if your text is wider than the StaticBox it will extend beyond the edge of the box (as least on OS X it does this, may behave differently on Windows).
Update:
On Windows the sizing behaves much differently - the StaticBox just shrinks around the text.
Although I agree with bogdan that explicitly setting a window size with SetMinSize or SetMaxSize is probably not a good idea (e.g. if system font size changes and the contents no longer fits nicely into the size constraints you've set), the StaticText control shrinks to the size of its contents and appears to pull everything with it unless you explicitly force size limits on its container.
I suspect your only option here is either to use SetMaxSize or SetMinSize on your box control, or try other control options other than a StaticText. You could try the HtmlWindow as an alternative.
Related
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.
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.
I am using PyQt5 for my application and a QTreeWidget to display content. Since I need to display rich text (HTML) each item has its text property set to "" and I create individual QLabels with the desired text. I then use QTreeWidget.setItemWidget. My problem is that using that method, when the QTreeWidget is smaller (in width) than the items' width, the horizontal scrollbar is not displayed. Which is logical, since from the point of view of the QTreeWidget, each item has width 0 because its text is empty.
I tried using a custom helper method that I use instead of the QLabel.setText method by automatically calling QLabel.setFixedSize method afterwards, but it doesn't work very well (the size is off by 5 to 90 pixels each time).
How would it be possible to make the whole thing determine automatically when to show the scrollbar, and what width to use for them?
MCVE:
tree = QTreeWidget()
item = QTreeWidgetItem(tree)
label = QLabel()
label.setText("<b>some text here</b>")
tree.setItemWidget(item, 0, label)
I even struggled with the same problem and finally this solution works for me:
Set the treewidget header StretchLastSection to False
treeWidget.header()->setSectionResizeMode(column, QtWidgets.QHeaderView.ResizeToContents)
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
When I create a QMainWindow without explicitly specifying its dimensions, PyQt will give it a -let's say- "standard size" which is not the minimum that the window can get.
Can I set this size at will in any way?
My goal is to get this "standard size" according to the currently visible widgets, when I set the visibility of some widgets on/off.
QWidget.sizeHint holds the recommended size for the widget. It's default implementation returns the layout's preferred size if the widget has a layout. So if your dialog has a layout, just use sizeHint to get the recommended size which is the default one.
You want to look at QWidget.normalGeometry().
Note, the widget (or in this case, QMainWindow) must be first shown for this to return something other than (0,0)
You might try this command to set size:
QMainWindow.setIconSize (self, QSize iconSize)
Alternatively, one can set a size with the given width and height using:
PySide.QtCore.QSize.setWidth() PySide.QtCore.QSize.setHeight()