2
votes

I'm a beginner with Qt and I haven't understand yet the layout on centralWidget.

I have a custom QWidget subclass (with a .ui and the cpp class) that I want to add to the central Widget.

I'd like to understand how to say to the QMainWindow subclass to resize and fit the content whenever I add something.

I've tried with adjustSize method both on mainwindow and on centralWidget objects but nothing change..

Anyway, I'm adding the widget in this way:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    MyWidget *w = new Undistort();
    w->setParent(this->centralWidget());
}

some advice?

1
do you have a layout in the QMainWindow class? - headsvk
I have tried with both. A grid layout and no layout at all.. the main window does not changed it size.. - nkint
so you add the widget to the window programatically? you should show some code for us to help you - headsvk
you are right, see the edit - nkint
If MyWidget is supposed to be inside the central widget, you should add it to its layout: this->centralWidget()->layout()->addWidget(w);. Remember to set a layout to your central widget if you haven't already. If you want MyWidget to be the central widget: this->setCentralWidget(w); - thuga

1 Answers

1
votes

Given example, depending on Pixmap size, QMainWindow will resize. Generally this is not the ideal case, as a user MainWindow need to display on the desktop, It should not be more that your desktop screen size. I am not sure you are actually looking for this. Copied fromSO Ans

#include "mainwindow.h"
#include <QLabel>
#include <QHBoxLayout>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindowClass)
{
    ui->setupUi(this);

    QPixmap pix;
    pix.load("C:\\Users\\user\\Desktop\\Uninstallation failure2.png");

    //Replace with  ImageLabel2
    QLabel* image = new QLabel(this);
    image->setPixmap(pix);

    QHBoxLayout* hbox = new QHBoxLayout(this);
    hbox->addWidget(image);
    QWidget* centreWidget = new QWidget();

    //QMainwindow, having a feature called centreWidget, to set the layout.
    centreWidget->setLayout( hbox ); 
    setCentralWidget( centreWidget );
}