I have a QHBoxLayout which I add widgets to, one by one.
I alternate by adding a Custom Widget, than a QLabel (repeating).
The QHBoxLayout is owned by a QGroupBox.
However, I notice that the spacing between the Custom Widget and the QLabel is 'irregular' when there are few widgets added to the Layout.
I intend for the QLabels to be centered in the gap between the custom widgets, but the QLabels only approach the centre as more widgets are added.
These screenshots show the two cases.
The desired case (only occuring with lots of widgets in the layout),
and the undesired case (occuring when little widgets are in the layout).
As you can see in the bottom case, the QLabels are not centered between the Custom Widgets. Instead, they are very far to the right!
What is causing this behaviour??
I believe the QGroupBox has a centered (horizontal) alignment and the QLabels have a fixed width of 10 (or 20 for the '->' QLabel) pixels (to avoid ugly overlap).
Any help at all would be greatly appreciated!
Thanks!
Specs:
python 2.7.1
PyQt4
Windows 7
The instantiation of the QHBoxLayout is absolutely normal and similiar to all examples.
Here is the code for the filling of the layout.
for i in range (0,len(Reactants)):
self.WidgetHouse.Reaction_Element_Layout.addWidget(eval('self.OverallContainer_Reactants.Reactant_'+str(i)))
# self.WidgetHouse.Reaction_Element_Layout is the QHBoxLayout
# self.OverallContainer_Reactants.Reactant_'+str(i) is a Custom Widget
if i != (len(Reactants)-1):
tmp = QtGui.QLabel('+')
tmp.setFixedWidth(10)
tmp.setAlignment(QtCore.Qt.AlignCenter)
self.WidgetHouse.Reaction_Element_Layout.addWidget(tmp)
else:
tmp = QtGui.QLabel('->')
tmp.setFixedWidth(20)
tmp.setAlignment(QtCore.Qt.AlignCenter)
self.WidgetHouse.Reaction_Element_Layout.addWidget(tmp)
EDIT:
Setting a fixed width of the QLabels (tmp.setFixedWidth(10)) is the source of the 'right anchoring'.
However, not setting a fixed width results in the same space being dedicated to QLabels and Custom Widgets in the layout, leading to an overlap of QLabels and Custom Widgets.
Identical to the code above, discluding 'tmp.setFixedWidt(10)'
What can I do to prevent this that's not completely horrible?
Can I move the Labels 'back' from the front?
(Calling .raise_() on all the custom widgets after everything was added to the layout did not work)
(Or will I have to do something like manually calculate the appropriate width of the labels based off the amount of widgets in the layout? Yuck!)
ANOTHER EDIT:
Progress:
I do not change the maximum/minimum (or fixed) width of the QLabels, but I do set their alignment to center.
Instead, I set a minimum width of the custom widget.
This fixes the apparent 'overlapping' (which wasn't really the case) and makes the Labels appear 'more centered'.
However, as you can see, the QLabels still aren't perfectly centered - too far right.
If I don't set a center alignment on the QLabels they are too far left.
What could be the problem now??
(I do not set a maximum width on the labels)
Thanks for all the help so far guys!
Here is a simple example script which is a reasonable approximation of the UI in the question, but without any of the layout issues:
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.groupBox = QtGui.QGroupBox(self)
hbox = QtGui.QHBoxLayout(self.groupBox)
length = 3
for index in range(length):
hbox.addWidget(Widget(u'H\u2082O', self))
if index < length - 1:
hbox.addWidget(Label(u'+', self))
else:
hbox.addWidget(Label(u'\u2192', self))
hbox.addWidget(Widget(u'4 H\u2082O', self))
hbox.addWidget(Label(u'+', self))
hbox.addWidget(Widget(u'H\u2084O\u2082', self))
vbox = QtGui.QVBoxLayout(self)
vbox.addWidget(self.groupBox)
vbox.addStretch()
class Label(QtGui.QLabel):
def __init__(self, label, parent=None):
QtGui.QLabel.__init__(self, label, parent)
self.setAlignment(QtCore.Qt.AlignCenter)
class Widget(QtGui.QWidget):
def __init__(self, label, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setMaximumWidth(100)
layout = QtGui.QGridLayout(self)
self.label = QtGui.QLabel(label, self)
self.label.setAlignment(QtCore.Qt.AlignCenter)
layout.addWidget(self.label, 0, 0, 1, 2)
self.lineEdit = QtGui.QLineEdit(self)
layout.addWidget(self.lineEdit, 1, 0, 1, 2)
self.toolButton = QtGui.QToolButton(self)
layout.addWidget(self.toolButton, 2, 0, 1, 1)
self.comboBox = QtGui.QComboBox(self)
layout.addWidget(self.comboBox, 2, 1, 1, 1)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Solution to all problems:
Give the custom widgets a fixed width.
Results in perfectly centered, not 'overlapping' widgets.
:)
Thanks for all the help guys!
Related
I'm trying to make a simple image editor GUI using the GridLayout. However, I am coming across a problem where the ratios between the image and the side panels are not what I want them to be. Currently, my code is:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Window(QMainWindow):
def __init__(self, parent = None):
super().__init__(parent)
self.setWindowTitle("PyEditor")
self.setGeometry(100, 100, 500, 300)
self.centralWidget = QLabel()
self.setCentralWidget(self.centralWidget)
self.gridLayout = QGridLayout(self.centralWidget)
self.createImagePanel()
self.createDrawPanel()
self.createLayerPanel()
def createImagePanel(self):
imageLabel = QLabel(self)
pixmap = QPixmap('amongus.png')
imageLabel.setPixmap(pixmap)
self.gridLayout.addWidget(imageLabel, 0, 0, 3, 4)
def createDrawPanel(self):
drawPanel = QLabel(self)
drawLayout = QVBoxLayout()
drawPanel.setLayout(drawLayout)
tabs = QTabWidget()
filterTab = QWidget()
drawTab = QWidget()
tabs.addTab(filterTab, "Filter")
tabs.addTab(drawTab, "Draw")
drawLayout.addWidget(tabs)
self.gridLayout.addWidget(drawPanel, 0, 4, 1, 1)
def createLayerPanel(self):
layerPanel = QLabel(self)
layerLayout = QVBoxLayout()
layerPanel.setLayout(layerLayout)
tab = QTabWidget()
layerTab = QWidget()
tab.addTab(layerTab, "Layers")
layerLayout.addWidget(tab)
self.gridLayout.addWidget(layerPanel, 1, 4, 1, 1)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
This gives me the following window:
When I resize the window, only the filter/draw and layer panels are stretching, and not the image panel. I want to image panel to stretch as well and take up the majority of the window instead.
While theoretically every Qt widget could be used as a container, some widgets should not be used for such a purpose, as their size hints, size policies and resizing have different and specific behavior depending on their nature.
QLabel is intended as a display widget, not as a container. Everything related to its size is based on the content (text, image or animation), so the possible layout set for it will have no result in size related matters and will also create some inconsistencies in displaying the widgets added to that layout.
If a basic container is required, then basic QWidget is the most logical choice.
Then, if stretching is also a requirement, that should be applied using the widget or layout stretch factors. For QGridLayout, this is achieved by using setColumnStretch() or setRowStretch().
Trying to use the row or column span is not correct for this purpose, as the spanning only indicates how many grid "cells" a certain layout item will use, which only makes sense whenever there are widgets that should occupy more than one "cell", exactly like the spanning of a table.
So, the following changes are required to achieve the wanted behavior:
change all QLabel to QWidget (except for the label that shows the image, obviously);
use the proper row/column spans; the imageLabel should be added with only one column span (unless otherwise required):
self.gridLayout.addWidget(imageLabel, 0, 0, 3, 1, alignment=Qt.AlignCenter)
set a column stretch of (at least) 1 for the first column:
self.gridLayout.setColumnStretch(0, 1)
if you want the image to be center aligned in the available space, set the alignment on the widget (not when adding it to the layout):
imageLabel = QLabel(self, alignment=Qt.AlignCenter)
Note that all the above will not scale the image whenever the available size is greater than that of the image. While you can set the scaledContents to True, the result will be that the image will be stretched to fill the whole available space, and unfortunately QLabel doesn't provide the ability to keep the aspect ratio. If you need that, then it's usually easier to subclass QWidget and provide proper implementation for size hint and paint event.
class ImageViewer(QWidget):
_pixmap = None
def __init__(self, pixmap=None, parent=None):
super().__init__(parent)
self.setPixmap(pixmap)
def setPixmap(self, pixmap):
if self._pixmap != pixmap:
self._pixmap = pixmap
self.updateGeometry()
def sizeHint(self):
if self._pixmap and not self._pixmap.isNull():
return self._pixmap.size()
return super().sizeHint()
def paintEvent(self, event):
if self._pixmap and not self._pixmap.isNull():
qp = QPainter(self)
scaled = self._pixmap.scaled(self.width(), self.height(),
Qt.KeepAspectRatio, Qt.SmoothTransformation)
rect = scaled.rect()
rect.moveCenter(self.rect().center())
qp.drawPixmap(rect, scaled)
I set the size policy of items in a QSplitter but it doesn't seem to affect anything. When I resize the window in the example below I want my left widget to stop growing once it reaches its size hint (QSizePolicy.Preferred) and the right widget to expand as big as possible (QSizePolicy.Expanding).
It works if I put them in a layout:
from PyQt5 import QtWidgets, QtCore
app = QtWidgets.QApplication([])
class ColoredBox(QtWidgets.QFrame):
def __init__(self, color):
super().__init__()
self.setStyleSheet(f'background-color: {color}')
def sizeHint(self) -> QtCore.QSize:
return QtCore.QSize(200, 200)
box1 = ColoredBox('red')
box2 = ColoredBox('green')
splitter = QtWidgets.QHBoxLayout()
splitter.setContentsMargins(0, 0, 0, 0)
splitter.setSpacing(0)
splitter.addWidget(box1)
splitter.addWidget(box2)
box1.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
box2.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
container = QtWidgets.QWidget()
container.setLayout(splitter)
container.show()
app.exec_()
But it doesn't work if I put them in a QSplitter, the splitter just splits space between them evenly:
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt
app = QtWidgets.QApplication([])
class ColoredBox(QtWidgets.QFrame):
def __init__(self, color):
super().__init__()
self.setStyleSheet(f'background-color: {color}')
def sizeHint(self) -> QtCore.QSize:
return QtCore.QSize(200, 200)
box1 = ColoredBox('red')
box2 = ColoredBox('green')
splitter = QtWidgets.QSplitter(Qt.Horizontal)
splitter.setStretchFactor(0, 0)
splitter.setStretchFactor(1, 1)
splitter.addWidget(box1)
splitter.addWidget(box2)
box1.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
box2.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
container = QtWidgets.QMainWindow()
container.setCentralWidget(splitter)
container.show()
app.exec_()
Layout vs Splitter:
The problem comes from the fact that you're setting the stretch factor too early.
setStretchFactor() is ignored if done on a widget index that doesn't exist yet (see the source code for its implementation);
QSplitter resizes the widget proportions based on their size policy; the size policy also includes the horizontal and vertical stretch factors, and they're reset to the 0 default value whenever set again with the basic setSizePolicy(horizontalPolicy, verticalPolicy) (which means that you can specify the stretch in the QSizePolicy, which is the same as using setStretchFactor).
The solution is simple: move the setStretchFactor lines after adding the widgets and setting their policies.
Obviously, a possible alternative is to set the maximum dimension (based on the QSplitter orientation), but that is not exactly the same thing.
If all widgets in the splitter have a maximum size (including situations for which only one widget exists), the result is that the splitter will have a maximum size based on those widgets, depending on other widgets in (or "above") its layout, but if the splitter is the top level window then there will be some blank space remaining whenever it's resized to a size bigger than the maximum of its child[ren].
I am trying to create a dynamic GUI with multiple Groupbox objects in a QVBoxLayout. As there are a lot of them, I will be needing a scroll area to make them available to the end user.
So I tried to change to top widget of this tab from a QWidget to a QScrollArea.
Before the change:
This is the kind of result I want but with a scroll bar because the window is too high.
After the change to QScrollArea:
My GroupBoxs are now "collapsed" and there is not scrollbar. I tried setting their size but it is not adequate because they are not fixed. I searched the documentation and tried to use WidgetResizable or I tried to set a fixed height or the sizehint but nothing worked as I wanted.
After creating the the Groupbox, the sizeHint for my QScrollArea is already very low (around 150px of height) so I think I'm missing a parameter.
It would be complicated to provide code as it is intricate. If necessary I could recreate the problem in a simpler way.
How to reproduce:
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import *
import sys
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
v_layout = QVBoxLayout()
scroll_area = QScrollArea()
self.layout().addWidget(scroll_area)
scroll_area.setLayout(v_layout)
# v_layout.setSizeConstraint(QLayout.SetMinimumSize)
for i in range(50):
box = QGroupBox()
grid = QGridLayout()
box.setLayout(grid)
grid.addWidget(QLabel("totototo"), 0, 0)
grid.addWidget(QLineEdit(), 1, 0)
grid.addWidget(QPushButton(), 2, 0)
v_layout.addWidget(box)
self.show()
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Uncommenting # v_layout.setSizeConstraint(QLayout.SetMinimumSize) allows the content of the group boxes to deploy and fixes the first part of the issue. But there is still not scroll bar.
You have 2 errors:
A widget should not be added to the layout of a QMainWindow, but the setCentralWidget method should be used.
You should not add the layout to the QScrollArea but use a widget as a container for the other widgets, also if you use layouts then you have to activate the widgetResizable property.
Considering the above, the solution is:
def initUI(self):
scroll_area = QScrollArea(widgetResizable=True)
self.setCentralWidget(scroll_area)
container = QWidget()
scroll_area.setWidget(container)
v_layout = QVBoxLayout(container)
for i in range(50):
box = QGroupBox()
grid = QGridLayout()
box.setLayout(grid)
grid.addWidget(QLabel("totototo"), 0, 0)
grid.addWidget(QLineEdit(), 1, 0)
grid.addWidget(QPushButton(), 2, 0)
v_layout.addWidget(box)
self.show()
I'm trying to make a widget which contains many other widgets and I keep having problems with resizing the window: the widget keeps expanding even if I "tell" it not to. Here is my minimal example:
from PyQt5 import QtWidgets, QtGui, QtCore
class CustomWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.layout = QtWidgets.QGridLayout()
self.button1 = QtWidgets.QPushButton("Button A")
self.button2 = QtWidgets.QPushButton("Button B")
self.label1 = QtWidgets.QLabel("Long label that can span multiple columns")
self.layout.addWidget(self.button1, 0, 0)
self.layout.addWidget(self.button2, 0, 1)
self.layout.addWidget(self.label1, 1, 0, 1, 2)
self.setLayout(self.layout)
class App(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.cw = CustomWidget()
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.cw)
self.setLayout(self.layout)
self.show()
QtWidgets.QApplication.setStyle(QtWidgets.QStyleFactory.create("Fusion"))
app = QtWidgets.QApplication([])
win = App()
status = app.exec_()
This code does work however if I resize the window then all the buttons and labels get spread out over the screen which is not what I want.
I've tried:
Setting a fixed size: doesn't work because the label text can be different lengths and I want the widget to resize accordingly (but stay as small as possible)
self.setFixedSize(self.size()) doesn't do anything and sometimes makes it worse
self.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) or any other size policy seems to do nothing
TL;DR I want my widget to shrink even if there's empty space but I don't want to set a fixed size.
EDIT:
I have partially solved the problem by passing in alignment=QtCore.Qt.AlignLeft to all the self.layout.addWidget calls. It doesn't totally get rid of the problem however it may be a step in the right direction.
If you want to keep those widgets as small as possible, you can add a row and column stretch to the layout, set for a row/column index greater than the most bottom-right layout coordinate used.
In your case, you have two rows and two columns, so it's enough to set the stretch for the third row and column:
self.layout.setColumnStretch(2, 1)
self.layout.setRowStretch(2, 1)
Obviously, you can set it for a very high index, so that if you have to add more widgets you don't have to care about it.
If you want to keep those widgets in the center, just add them starting from the second row and column and set the row/column stretch for the first row/column too:
self.layout.setColumnStretch(0, 1)
self.layout.setRowStretch(0, 1)
self.layout.addWidget(self.button1, 1, 1)
self.layout.addWidget(self.button2, 1, 2)
self.layout.addWidget(self.label1, 2, 1, 1, 2)
self.layout.setColumnStretch(3, 1)
self.layout.setRowStretch(3, 1)
Note that you can also use the size policy, but you have to use Maximum, not Minimum, and you also need to add widgets with the correct alignment.
I got same issue. I resolved the issue by setting the values of minimum and maximum size to equal like both to 100
If you want to shrink the widget set minimum to 0 and set maximum value to the size you want start the display. It will not expand but shrink
From what you are describing it seems you just don't want to use a layout.
Make a widget with a layout to hold the buttons and label. Place this widget in the main window without using a layout, instead place with setGeometry.
Something like this,
from PyQt5 import QtWidgets, QtGui, QtCore
class CustomWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.resize(400, 100)
# Create a widget to hold your buttons
self.fixwidget = QtWidgets.QWidget(self)
self.layout = QtWidgets.QGridLayout()
self.button1 = QtWidgets.QPushButton("Button A")
self.button2 = QtWidgets.QPushButton("Button B")
self.label1 = QtWidgets.QLabel("Long label that can span multiple columns")
self.layout.addWidget(self.button1, 0, 0)
self.layout.addWidget(self.button2, 0, 1)
self.layout.addWidget(self.label1, 1, 0, 1, 2)
# set the layout inside the widget
self.fixwidget.setLayout(self.layout)
# place the widget with setGeometry
height = self.fixwidget.sizeHint().height()
width = self.fixwidget.sizeHint().width()
xpos, ypos = 5, 5
self.fixwidget.setGeometry(QtCore.QRect(xpos, ypos, width, height))
QtWidgets.QApplication.setStyle(QtWidgets.QStyleFactory.create("Fusion"))
app = QtWidgets.QApplication([])
win = CustomWidget()
win.show()
status = app.exec_()
Notice that not using a layout is, in most cases, not advised as it makes managing the window harder.
Consider the case of a QMainWindow with a QWidget as central widget. This widget has a QHBoxLayout. I add two other widgets to it, each with a QVBoxLayout.
I now want to bring the Widgets inside QVBoxLayout closer to each other. The attempt is to use .setMargin(0), .setSpacing(0) and .setContentsMargins(0,0,0,0) for this purpose.
However the result is that their separation is actually increased instead of decreased - as can be seen in the picture (where Gain is the widget where I set the margins and spacings to zero).
The code to reproduce this issue is appended below. (And the same actually happens when using a QGridLayout.)
Here is the question on two different complexity levels:
(a) Since the only difference between the two widgets is that one has the margins and spacings set to zero, one of the used method calls must have done something else to the layout or widget-properties. Which other property is changed by setting any of .setMargin(0), .setSpacing(0) and setContentsMargins(0,0,0,0) ?
(b) How do I make the spacing between the text label and the combobox in this example smaller?
from PyQt4 import QtGui
import sys
class LabeledComboBox(QtGui.QWidget):
def __init__(self, text="", items=[], parent=None):
super(LabeledComboBox, self).__init__(parent)
self.parent = parent
self.widgetlayout = QtGui.QVBoxLayout(self)
self.widgetlayout.addWidget(QtGui.QLabel(text))
self.Combo = QtGui.QComboBox()
self.Combo.addItems(items)
self.widgetlayout.addWidget(self.Combo)
self.parent.mylayout.addWidget(self)
def printParams(self):
# print some margin/spacing parameters for testing
m = self.widgetlayout.margin()
s = self.widgetlayout.spacing()
cm = self.widgetlayout.getContentsMargins()
print "margin: {m}, spacing: {s}, ContentsMargin: {cm}".format(m=m, s=s, cm=cm)
class App(QtGui.QMainWindow):
def __init__(self, parent=None):
super(App, self).__init__(parent)
self.mainbox = QtGui.QWidget()
self.mylayout = QtGui.QHBoxLayout()
self.mainbox.setLayout(self.mylayout)
self.setCentralWidget(self.mainbox)
self.GainWidget = LabeledComboBox("Gain", ['low', 'medium', 'high'], self)
self.RevolutionsWidget = LabeledComboBox("Revolutions", ['100', '200', '400'], self)
self.GainWidget.printParams()
# this outputs: margin: 9, spacing: 6, ContentsMargin: (9, 9, 9, 9)
# now I set everything to zero
self.GainWidget.widgetlayout.setMargin(0)
self.GainWidget.widgetlayout.setSpacing(0)
self.GainWidget.widgetlayout.setContentsMargins(0,0,0,0)
# check
self.GainWidget.printParams()
# margin: 0, spacing: 0, ContentsMargin: (0, 0, 0, 0)
if __name__=='__main__':
app = QtGui.QApplication(sys.argv)
thisapp = App()
thisapp.show()
sys.exit(app.exec_())
Firstly: setMargin is an obsolete method which has beed superseded by setContentsMargins, so you can ignore it.
Secondly: the increase in separation is caused by setting the margins to zero. The two vertical layouts are in the same horizontal layout, so they will necessarily have the same height. But the left-hand layout has no margins, so it has more space available to stretch out in. If both vertical layouts have the same settings, their child widgets can be squeezed closer together by resizing the window.
So you need to use setSpacing on both layouts to change the spacing.
In the latest PyQt 5.10 setContentsMargins method is working well.
You may create a layout for your widget and then apply its margins.
widget.layout.setContentsMargins(0,0,0,0)