Hi!
I’m trying to create a collapsible dock widget, by subclassing its content widget to override the sizeHint() method.
It almost works, but when the dock widget gets resized by the user, the size hint is no longer considered.
Here’s a minimal example (some stacked dock widgets and two push buttons to collapse/expand them):
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QtWidgets/QWidget>
#include <QtWidgets/QMainWindow>
// Content of the dock widgets
class MyWidget : public QWidget
{
Q_OBJECT
private:
bool isClosed;
public slots:
void setClosed(bool value)
{
if (value != isClosed)
{
isClosed = value;
// sizeHint() is changed
updateGeometry();
// None of these works :(
// ((QMainWindow *)(parent()))->updateGeometry();
// ((QMainWindow *)(parent()))->adjustSize();
}
}
// Wrapper
void collapse() { setClosed(true); }
void expand() { setClosed(false); }
public:
MyWidget(QWidget *parent = NULL)
: QWidget(parent)
{
isClosed = false;
}
QSize sizeHint() const
{
if (isClosed)
return QSize(0, 0);
else
return QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
}
};
#endif
Main Window
#include "ProvaDock.h"
#include "MyWidget.h"
#include <QtWidgets/QDockWidget>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QHBoxLayout>
ProvaDock::ProvaDock(QWidget *parent)
: QMainWindow(parent)
{
// Create the central widget
QPushButton *btnCollapse = new QPushButton(tr("Collapse"));
QPushButton *btnExpand = new QPushButton(tr("Expand"));
QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(btnCollapse);
layout->addWidget(btnExpand);
// Setup the central widget
QWidget *contents = new QWidget();
contents->setLayout(layout);
setCentralWidget(contents);
// Number of dock widgets to be added
const unsigned int NDOCKS = 3;
QDockWidget *lastDock = NULL;
for (unsigned int i = 0; i < NDOCKS; i++)
{
// Create the dock widget
const QString title = tr("Dock %1").arg(i + 1);
QDockWidget *newDock = new QDockWidget(title, this);
newDock->setWidget(new MyWidget(newDock));
// Add the dock widget to main window
addDockWidget(Qt::BottomDockWidgetArea, newDock, Qt::Horizontal);
// Tabify with the last one
if (lastDock)
tabifyDockWidget(lastDock, newDock);
// Signals
QObject::connect(btnCollapse, SIGNAL(clicked()), (MyWidget *)(newDock->widget()), SLOT(collapse()));
QObject::connect(btnExpand, SIGNAL(clicked()), (MyWidget *)(newDock->widget()), SLOT(expand()));
// Track the last dock widget added
lastDock = newDock;
}
showMaximized();
}
I read that QMainWindow handles dock widgets with an internal layout, which unfortunately is inaccessible to the programmer.
Is there a way to “reset” the internal state of this layout (in order to take into account the size hint again)?
Thanks
↧