Home > Software design >  Is it possible to constrain a Qt parent QWidget to always be the same size as its child QWidget?
Is it possible to constrain a Qt parent QWidget to always be the same size as its child QWidget?

Time:01-13

I've written a simple "proxy widget" class in Qt; the idea is that this widget will hold a single child QWidget and represent that widget in the QWidget hierarchy. (FWIW, the motivation for doing this is to make it easy to screenshots of example program, with and without "proxy" keyword supplied

#include <QApplication>
#include <QStackedLayout>
#include <QWidget>

class ProxyWidget : public QWidget
{
public:
   ProxyWidget(QWidget * childWidget)
      : _childWidget(childWidget)
      , _layout(new QStackedLayout(this))
   {
      _layout->addWidget(childWidget);
      setSizePolicy(childWidget->sizePolicy());
   }

   virtual QSize sizeHint() const {return _childWidget->sizeHint();}
   virtual QSize minimumSizeHint() const {return _childWidget->minimumSizeHint();}

private:
   QWidget * _childWidget;
   QStackedLayout * _layout;
};

static void SetWidgetBackgroundColor(QWidget * w, const QColor bc)
{
   QPalette p = w->palette();
   p.setColor(QPalette::Window, bc);
   w->setAutoFillBackground(true);
   w->setPalette(p);
}

int main(int argc, char ** argv)
{
   QApplication app(argc, argv);

   QWidget * win = new QWidget;
   win->setWindowTitle("Proxy Widget test");

   QWidget * proxyMe = new QWidget;
   proxyMe->setFixedSize(100, 50);
   SetWidgetBackgroundColor(proxyMe, Qt::blue);

   QBoxLayout * winLayout = new QBoxLayout(QBoxLayout::TopToBottom, win);

   if ((argc >= 2)&&(strcmp(argv[1], "proxy") == 0))
   {
      ProxyWidget * proxyWidget = new ProxyWidget(proxyMe);
      SetWidgetBackgroundColor(proxyWidget, Qt::red);

      winLayout->addWidget(proxyWidget);
   }
   else winLayout->addWidget(proxyMe);

   win->show();
   return app.exec();
}

CodePudding user response:

I guess minimumSize and maximumSize of ProxyWidget is different from its child widget and setting them fix things in your particular example :

ProxyWidget(QWidget * childWidget)
        : _childWidget(childWidget)
        , _layout(new QStackedLayout(this))
    {
        _layout->addWidget(childWidget);
        setSizePolicy(childWidget->sizePolicy());

        this->setMinimumSize(childWidget->minimumSize());
        this->setMaximumSize(childWidget->maximumSize());
    }

However i am not sure it's the best solution but it might gives you a hint to a better one.

  • Related