Search code examples
qtqt5qtgui

QMainWindow : Set widgets size with respect to screen size


I have a Qt class which inherits from QMainWindow. The constructor of the class creates two widgets which are added to a horizontal layout object as follows:

MyWindow::MyWindow()
{
    resize(QDesktopWidget().availableGeometry(this).size());
    display = new MyWidget(this);
    display->setSizePolicy(QSizePolicy::Expanding, 
                           QSizePolicy::Expanding);

    current = new MyWidget(this);
    current->setSizePolicy(QSizePolicy::Expanding, 
                           QSizePolicy::Expanding);

    QHBoxLayout *layout = new QHBoxLayout();
    layout->addWidget(display);
    layout->addWidget(current);

    QFrame* frame = new QFrame();
    frame->setFrameShape(QFrame::StyledPanel);
    frame->setLayout(layout);
    setCentralWidget(frame);

    show();
}

This currently shows the widget side of side of each other. However, what I would like to do is have one of the widgets take 30% of the horizontal space while the other one occupies the other 70%. I would also like the widgets to expand or contract if one resizes the main window but keeping these ratios.


Solution

  • When you place a widget into a layout you can specify its stretch factor:

    QHBoxLayout *layout = new QHBoxLayout();
    layout->addWidget(display, 3);
    layout->addWidget(current, 7);
    

    http://doc.qt.io/qt-5/qboxlayout.html#addWidget