How to make QLineEdit expand inside QScrollArea - qt

I have a QLabel and a QLineEdit inside a QWidget. When I have the widget inside a QScrollArea, the line edit does not expand to occupy the excess width of the window. When the widget is not inside the scroll area, it does expand.
I've tried setting the size policy of the line edit and the widget, to expand horizontally, but it doesn't occupy the excess space. I suspect the sizeHint() of the widget is compacted when inside a scroll area. Any ideas how to make this work?
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self, None)
self.setWindowTitle('Test Window')
self.resize(500, 250)
scrollArea = QtGui.QScrollArea()
scrollWidget = QtGui.QWidget()
scrollWidget.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Maximum)
layout = QtGui.QGridLayout(scrollWidget)
label = QtGui.QLabel("Name:")
layout.addWidget(label, 0, 0)
lineEdit = QtGui.QLineEdit("Value")
lineEdit.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Maximum)
layout.addWidget(lineEdit, 0, 1)
scrollWidget.setLayout(layout)
scrollArea.setWidget(scrollWidget)
self.setCentralWidget(scrollArea)

I believe I have solved your problem.
Make the following addition to your code and it should behave correctly:
...
scrollArea.setWidget(scrollWidget)
scrollArea.setWidgetResizable(True) #add this
self.setCentralWidget(scrollArea)
...
From the docs,
widgetResizable : bool
This property holds whether the scroll area should resize the view widget.
If this property is set to true, the scroll area will automatically resize the widget in order to avoid scroll bars where they can be avoided, or to take advantage of extra space.

Related

How to calculate QTextEdit height accurately by its contents to get rid of vertical scrollbars?

I need a QTextEdit widget which height grows or shrinks to the size of the inner content. I didn't find built-in solution and decided to make my own with connections to &QTextEdit::textChanged signals that will update size of the widget at runtime. In the code snippet I flattened my custom component to raw QTextEdit for simplicity. The problem is that calculation via QFontMetrics is inaccurate, a vertical scrollbar appears with only some pixels to scroll
I want to get rid of any vertical scrollbars in these text widgets.
However, I don't need to get rid of horizontal scrollbars and here is the second problem arises. Seemingly, horizontal scrolls occupy space in the viewport of the text widget and its internal height shrinks by the height of the scrollbar itself
void TestWindow::setupUi(QWidget *parent)
{
QVBoxLayout *v_box0 = new QVBoxLayout(parent);
v_box0->setContentsMargins(0, 0, 0, 0);
QVBoxLayout *v_scroll_layout = new QVBoxLayout();
v_scroll_layout->setContentsMargins(0, 0, 0, 0);
v_scroll_layout->setSpacing(0);
v_scroll_layout->setAlignment(::Qt::AlignTop);
QWidget *scroll_content = new QWidget();
scroll_content->setLayout(v_scroll_layout);
QScrollArea *v_scroll = new QScrollArea();
v_scroll->setWidgetResizable(true);
v_scroll->setWidget(scroll_content);
v_box0->addWidget(v_scroll);
QSize size;
QTextEdit *edit0 = new QTextEdit();
edit0->setLineWrapMode(QTextEdit::NoWrap);
edit0->setText("Hello World 1\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11");
edit0->setFont(viewer_font);
size = edit0->fontMetrics().size(0, edit0->document()->toPlainText());
edit0->document()->setDocumentMargin(0);
edit0->setMinimumHeight(size.height());
QTextEdit *edit1 = new QTextEdit();
edit1->setLineWrapMode(QTextEdit::NoWrap);
edit1->setText("New item");
edit1->setFont(viewer_font);
size = edit1->fontMetrics().size(0, edit1->document()->toPlainText());
edit1->document()->setDocumentMargin(0);
edit1->setMinimumHeight(size.height());
v_scroll_layout->addWidget(edit0);
v_scroll_layout->addWidget(edit1);
setFixedHeight(300);
}

Window resizing based on label size doesn't consider title bar in pyQT5

I'm coding a simple image viewer and would like for the window to resize based on the image that I open.
The window I'm using is a QMainWindow and has a toolbar. The only widget I have is a QLabel which is set as the central widget. When I open the image I use self.resize(self.label.sizeHint()), but the window size doesn't take into account the size of the title bar and the toolbar, so for example if I open a 400x400 image the window will be of the correct width, but a little bit too short.
What would be the correct way to calculate the correct window size so that it resizes correctly on every platform? (Windows, macOS, Linux)
EDIT: the minimal code is:
import PyQt5.QtWidgets as w
import PyQt5.QtGui as g
import PyQt5.QtCore as c
import sys
class ImageViewerWindow(w.QMainWindow):
def __init__(self):
super().__init__()
self.loadedImagePaths = []
self.imageIndex = 0
self.scrollArea = w.QScrollArea()
self.label = w.QLabel()
self.setCentralWidget(self.scrollArea)
self.scrollArea.setWidgetResizable(True)
self.label.setAlignment(c.Qt.AlignCenter)
self.label.setMinimumSize(1,1)
# Actions
self.openAction = w.QAction("Open...", self)
self.openAction.setShortcut(g.QKeySequence.Open)
self.openAction.triggered.connect(self.openMenuDialog)
# Toolbar elements
toolbar = w.QToolBar("Top toolbar")
toolbar.setMovable(False)
toolbar.setContextMenuPolicy(c.Qt.PreventContextMenu)
self.addToolBar(toolbar)
# Status bar elements
self.setStatusBar(w.QStatusBar(self))
# Add actions to toolbar and menu
toolbar.addAction(self.openAction)
def showImageAtIndex(self, index):
image = g.QPixmap(self.loadedImagePaths[index])
self.label.setPixmap(image)
self.scrollArea.setWidget(self.label)
self.imageIndex = index
self.angle = 0
self.label.adjustSize()
self.resize(self.label.sizeHint())
def openMenuDialog(self, firstStart = False):
self.loadedImagePaths, _ = w.QFileDialog.getOpenFileNames(parent=self, caption="Select one or more JPEG files to open:", filter="JPEG Image(*.jpg *.jpeg)")
if self.loadedImagePaths:
if firstStart:
self.show()
self.imageIndex = 0
self.showImageAtIndex(self.imageIndex)
elif firstStart:
sys.exit()
a = w.QApplication([])
ivw = ImageViewerWindow()
ivw.openMenuDialog(firstStart = True)
a.exec()
If you try and open an image and then resize the window you will notice that some of the image is covered by the title bar and the status bar.
The main problem is that using setWidgetResizable():
the scroll area will automatically resize the widget in order to avoid scroll bars where they can be avoided
So you have to remove that line, or use setFixedSize() on the label using the image size.
Then, calling adjustSize() on the label is not enough, as you actually need to call adjustSize() against the top level window: this is because calling resize() with the image size won't consider all other widgets in the window (in your case, the toolbar and status bar).
Unfortunately, that won't be enough, as QScrollArea caches the size hint of the widget, and calling again setWidget() with the same widget is useless.
The easiest solution is to use a subclass of QScrollArea and reimplement the sizeHint().
Finally, the alignment only has effect on the label contents, but when the widget is added to a container the alignment has to be set for the widget.
class ScrollAreaAdjust(w.QScrollArea):
def sizeHint(self):
if not self.widget():
return super().sizeHint()
frame = self.frameWidth() * 2
return self.widget().sizeHint() + c.QSize(frame, frame)
class ImageViewerWindow(w.QMainWindow):
def __init__(self):
super().__init__()
self.loadedImagePaths = []
self.imageIndex = 0
self.scrollArea = ScrollAreaAdjust()
self.label = w.QLabel()
self.setCentralWidget(self.scrollArea)
self.scrollArea.setWidget(self.label)
self.scrollArea.setAlignment(c.Qt.AlignCenter)
# ...
def showImageAtIndex(self, index):
image = g.QPixmap(self.loadedImagePaths[index])
self.label.setPixmap(image)
self.label.setFixedSize(image.size())
self.imageIndex = index
self.angle = 0
self.scrollArea.updateGeometry()
self.adjustSize()
Note that the size hint of a top level window will only be respected until the size doesn't exceed 2/3 of the screen size. This means that if the image will force the window to a slightly bigger size, at least one scroll bar will be shown, even if it's not strictly necessary.
There is no obvious nor universal solution for that, and you need to find your own way. For instance, you can check if the scroll bars are visible after adjusting the size and eventually compare the size of the image and that of the scroll area's viewport, then if one of the image dimensions is just smaller by the size of the opposite scroll bar, force a resizing of the top level window by that scroll bar size.

Fixed sized scroll area with layout.

What I want to do is to show new QWidget, which is set in QScrollArea.
The Grid Layout is set in Scroll Area and than VBox Layout is added to the Grid one.
Program allows to add dynamically Labels in this VBox Layout.
I want scroll area has fixed size and when area taken by Labels exceeds scroll area's size (heigth), than scrollbar should appear (and no changes in Scroll Area size).
With my code - adding Labels causes increasing heigth of QWidget (window).
Scrollbar can be seen at the beginning but at some point it disappears... like QScrollArea is no more in there...
QWidget* playlistWindow = new QWidget();
playlistWindow->setAcceptDrops(true);
playlistWindow->resize(200, 300);
QScrollArea* scrollArea = new QScrollArea();
scrollArea->setWidget(playlistWindow);
QVBoxLayout* layout = new QVBoxLayout();
QGridLayout* gridLayout = new QGridLayout();
layout->setAlignment(Qt::AlignTop);
scrollArea->setLayout(gridLayout);
gridLayout->addLayout(layout, 0, 0);
scrollArea->setMaximumHeight(300);
scrollArea->show();

Set Vertical Alignment of QFormLayout QLabel

I'm using PySide/PyQt, but this is a general Qt question.
Is there a way to set up a QFormLayout so that labels are centered vertically without having to explicitly create the QLabel's and set their vertical size policy to expanding first? When the widget in column 2 is taller than my label, I want my label to be centered vertically with the widget, rather than aligned with it's top...
Here's an example script that demonstrates the problem. I've colored the labels red to better demonstrate their size behavior.
from PySide import QtCore, QtGui
app = QtGui.QApplication([])
widget = QtGui.QWidget()
widget.setStyleSheet("QLabel { background-color : red}")
layout = QtGui.QFormLayout()
layout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow)
layout.setLabelAlignment(QtCore.Qt.AlignCenter)
editor1 = QtGui.QLineEdit()
editor1.setFixedSize(300, 100)
editor2 = QtGui.QLineEdit()
editor2.setFixedSize(300, 100)
layout.addRow('Input', editor1)
layout.addRow('Longer Named Input', editor2)
widget.setLayout(layout)
widget.show()
app.exec_()
Here's the outcome:
Here's an example that demonstrates the desired result by explicitly creating QLabel's and giving them an expanding size policy:
from PySide import QtCore, QtGui
app = QtGui.QApplication([])
widget = QtGui.QWidget()
widget.setStyleSheet("QLabel { background-color : red}")
layout = QtGui.QFormLayout()
layout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow)
layout.setLabelAlignment(QtCore.Qt.AlignCenter)
editor1 = QtGui.QLineEdit()
editor1.setFixedSize(300, 100)
editor2 = QtGui.QLineEdit()
editor2.setFixedSize(300, 100)
label1 = QtGui.QLabel('Input')
expand = QtGui.QSizePolicy.Expanding
label1.setSizePolicy(expand, expand)
label2 = QtGui.QLabel('Longer Named Input')
label2.setSizePolicy(expand, expand)
layout.addRow(label1, editor1)
layout.addRow(label2, editor2)
widget.setLayout(layout)
widget.show()
app.exec_()
And here's that outcome...
I've tried QFormLayout.setLabelAlignment() which doesn't appear to help. The docs even mention that setLabelAlignment only does the horizontal alignment of the labels (and even then doesn't appear to do centered, just left or right).
As an aside, this lead me to also try to set the horizontal alignment to centered, but that proved even harder since the labels don't expand horizontally to fill the space (small labels don't expand to match the biggest label). The only way I could get horizontally centered labels was to explicitly find the width of the biggest label, after showing the widget, then set all other labels to have the same width...
labels = [layout.itemAt(i*2).widget() for i in range(layout.rowCount())]
max_width = max(label.width() for label in labels)
for w in labels:
w.setFixedWidth(max_width)
w.setAlignment(QtCore.Qt.AlignCenter)
Which results in this:
Is there anything I'm missing at the QFormLayout level that will center the labels? Do I have to make QLabels and set to expanding or turn on expanding after the fact (like below)? Thanks for any ideas!
expand = QtGui.QSizePolicy.Expanding
labels = [layout.itemAt(i*2).widget() for i in range(layout.rowCount())]
for w in labels:
w.setSizePolicy(expand, expand)
"[2] Labels can only be aligned left (by default) or right" - I don't believe this is true.
Your code doesn't run for me, so I can't test your exact code. However, this method works for other widgets: notice the use of | to separate the various positional commands.
label2.setAlignment(PyQt5.QtCore.Qt.AlignLeft|PyQt5.QtCore.Qt.AlignVCenter)
I get this is a few years old, so you've probably come up with another way, but this method works well for me.
I don't think there is an elegant solution to your problem.
From QFormLayout's source code:
void QFormLayoutPrivate::arrangeWidgets(const QVector<QLayoutStruct>& layouts, QRect &rect)
{
// [...]
if (label) {
int height = layouts.at(label->vLayoutIndex).size;
if ((label->expandingDirections() & Qt::Vertical) == 0) {
/*
If the field on the right-hand side is tall,
we want the label to be top-aligned, but not too
much. So we introduce a 7 / 4 factor so that it
gets some extra pixels at the top.
*/
height = qMin(height,
qMin(label->sizeHint.height() * 7 / 4,
label->maxSize.height()));
}
[1] QSize sz(qMin(label->layoutWidth, label->sizeHint.width()), height);
int x = leftOffset + rect.x() + label->layoutPos;
[2] if (fixedAlignment(q->labelAlignment(), layoutDirection) & Qt::AlignRight)
[ ] x += label->layoutWidth - sz.width();
[ ] QPoint p(x, layouts.at(label->vLayoutIndex).pos);
// ### expansion & sizepolicy stuff
label->setGeometry(QStyle::visualRect(layoutDirection, rect, QRect(p, sz)));
}
// [...]
}
What do we see here?
[1] Labels do not stretch horizontally
[2] Labels can only be aligned left (by default) or right
So you have to either somehow manually synchronize labels' widths (e.g. set fixed one) or abandon QFormLayout and use QGridLayout instead.

Fill the QLabel/QGraphics widget placed in the grid with the image

I have placed two QGraphicsView's and one QLabel inside a horizontal layout (QHBoxLayout) with its layoutStretch set to 1, 1, 1. The problem is when I try to load images inside them, the images does not fill the widgets area. Here is the code:
QPixmap pix1("image1.jpg");
pix1 = pix1.scaled(ui->label1->size());
ui->label1->setPixmap(pix);
QPixmap pix2("image2.jpg");
pix2 = pix2.scaled(ui->graphicsView1->size());
ui->graphicsView1->scene()->addPixmap(pix2);
QPixmap pix3("image3.jpg");
pix3 = pix3.scaled(ui->graphicsView2->size());
ui->graphicsView2->scene()->addPixmap(pix3);
And here is the undesired output:
I have tried setting HorizontalPolicy and VerticalPolicy property of widget to Expanding and also Minimum, but none of them helped either.
Set size policy to QSizePolicy::Ignored and scale with Qt::KeepAspectRatioByExpanding:
ui->label1->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
pix1 = pix1.scaled(ui->label1->size(), Qt::KeepAspectRatioByExpanding);
ui->label1->setPixmap(pix);
You probably want to scale pixmaps in resizeEvent().

Resources