QSizePolicy::Minimum doesn't minimalize qwidget

985 Views Asked by At

I want to have the following layout in a Qt-C++ project: A VBoxLayout with in it two QTextEdits underneath each other. The top one should shrink to have the minimal size: 1 line of text if there's one line in it, bigger if there's more. The bottom one should take the remaining space in the window.

I now have the following code in the constructor of my mainwindow (which extends QMainWindow):

QWidget *mainpanewidget = new QWidget(this);
QVBoxLayout *mainpane = new QVBoxLayout(mainpanewidget);
this->setCentralWidget(mainpanewidget);

QTextEdit *firsttext = new QTextEdit(this);
firsttext->setText("first text");
QTextEdit *secondtext = new QTextEdit(this);
secondtext->setText("second text");

//first try: use sizepolicies
firsttext->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
secondtext->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

//second try: explicitely set minimum size to something small
firsttext->setMinimumHeight(10);
firsttext->setMinimumWidth(10);

//3th try: stretch factors
mainpane->setStretchFactor(firsttext,0);
mainpane->setStretchFactor(secondtext,1);

//4th try: size policy of surrounding layout
mainpanewidget->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);

mainpane->addWidget(firsttext);
mainpane->addWidget(secondtext);
mainpane->update();

With this code the second QTextEdit does become larger than the first one, but the first one seems to think it's minimal size should be 192 pixels (14 lines), which is far above it's real necessary number of lines: 1. This is the size given by sizehint, instead of minimalheight. Unfortunately there doesn't seem to be a way to adapt sizehint without subclassing QTextEdit.

I have tried different things, as can be seen in the above code, to come up with one minimal QTextEdit and one expanding. The only one that works is to set the maximumheight of the first QTextEdit, which is something I don't want to hardcode as the text in it may be larger than some limit I hardcode now. Plus hardcoding limits is not very good coding practice.

As I want to use similar sizing for different qwidgets in my application (QTextEdit, labels, buttons,...) I would prefer to not have to use inheritance, as this would bring in a lot of extra classes which all change but a single thing of their parent class.

I work in Qt 5.7.0.

Note: there seem to be a lot of questions regarding qsizepolicy and resizing in Qt. If I missed a duplicate of this question you are free to link it and close this one.

0

There are 0 best solutions below